先看示例:
#include <pthread.h> #include <stdio.h> #define errlog(errmsg) \ do { \ perror(errmsg); \ printf("--%s--%s--%d--\n", __FILE__, __FUNCTION__, __LINE__); \ return -1; \ } while (0) void *thread1_handler(void *arg) { int count = *((int *)arg); while (count > 0) { printf("thread1...\n"); sleep(1); count--; } pthread_exit("thread1...exit"); } void *thread2_handler(void *arg) { int count = *((int *)arg); while (count > 0) { printf("thread2...\n"); sleep(1); count--; } pthread_exit("thread2...exit"); } int main(int argc, const char *argv[]) { pthread_t thread1, thread2; int arg1 = 2; int arg2 = 5; void *retval; if (pthread_create(&thread1, NULL, thread1_handler, (void *)&arg1) != 0) { errlog("pthread_create1 error"); } if (pthread_create(&thread2, NULL, thread2_handler, (void *)&arg2) != 0) { errlog("pthread_create2 error"); } pthread_join(thread1, &retval); printf("%s\n", (char *)retval); pthread_join(thread2, &retval); printf("%s\n", (char *)retval); return 0; }点击复制复制失败已复制
上述代码中, thread1_handler
、 thread2_handler
分别为两个线程的执行代码,当两个线程任务执行结束之后,进行资源回收,并得到线程退出时的状态值并输出显示。
编译并运行,结果如下所示:
$ gcc main.c -lpthread && ./a.out thread1... thread2... thread1... thread2... thread2... thread1...exit thread2... thread2... thread2...exit点击复制复制失败已复制
由运行结果可以看出,两个线程分别向终端输出是并发执行的,注意输出先后是不固定的,只是在本次运行时, thread1
先输出(原书中可是 thread2
先输出的)。同时,也可以看出线程执行函数与封装子函数的区别。如果将线程函数想象成一个在主函数中封装的子函数,那么子函数必然会按照代码的顺序依次执行,即执行完 thread1
再执行 thread2
。