c语言线程

Posted on 2012-05-18 13:05  逝水如年  阅读(466)  评论(0)    收藏  举报
 1 #include <pthread.h>
 2 #include <unistd.h>
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #include <string.h>
 6 pthread_t ntid;
 7 /**
 8  *  功能:打印进程id,打印线程id。
 9  *  在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库
10  *  gcc pthread.c -lpthread -o pthread
11  */
12 void printids(const char *s)
13 {
14     pid_t pid;
15     pthread_t tid;
16     //获取当前进程id
17     pid = getpid();
18     //获取当前线程id
19     tid = pthread_self();
20     //打印当前进程id,打印当前线程id
21     printf("%s pid %u strerrortid %u (0x%x)\n", s, \
22     (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
23 }
24 
25 void *th_fn(void *arg)
26 {
27     printids(arg);
28     return NULL;
29 }
30 
31 int main(void)
32 {
33 
34     int err = 0;
35     err = pthread_create(&ntid, NULL, th_fn, "new thread: ");
36     if (err != 0) {
37         fprintf(stderr, "errno: %s", strerror(err));
38         exit(1);
39     }
40     printids("main thread: ");
41     //为了不让进程比线程提前结束,延迟1秒执行
42     sleep(1);
43     return 0;
44 }

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3