线程创建与销毁

thread_functionmessage); pthread_create(&a_thread, NULL, thread_function, (void *)num);原型: #include <pthread.h>int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restrict attr,void *(*start_routine)(void*),void *restrict arg);thread: 创建成功返回的线程IDattr: 线程属性, 该参数一般为NULL, 为默认的线程属性start_routine: 回调函数指针, 创建线程成功, 该线程所以执行的函数arg: 函调函数的入参. 若为void, 则写NULL.

2. pthread_join(a_thread, &thread_result);pthread_join – wait for thread termination#include <pthread.h>int pthread_join(pthread_t thread, void **value_ptr);thread: 主线程所要等待的副线程ID结束(也就是该副线程是由主线程的基础上创建的), 该函数由于收集线程终止, 然后释放该线程所占有的资源.value_ptr: 该线程thread所调用的函数中, 由 pthread_exit(void *value_ptr)指定传回. 但是还有一点疑问:

; pthread_exit((void*)num);pthread_exit – thread termination#include <pthread.h>void pthread_exit(void *value_ptr);该函数是在线程创建函数pthread_create函数中, 由自定义处理函数start_routine中显示定义传回的参数. 即pthread_exit所接收的参数即传出到pthread_join()中最后一个参数的值.

1 /******************************************************************************* 2 * 版权所有: 3 * 模 块 名: 4 * 文 件 名:pthread1.c 5 * 实现功能: 6 * 作 者:XYZ 7 * 版 本:V1.0 8 * 日 期:2013.07.24 9 * 联系方式:xiao13149920@foxmail.com#include<stdio.h>13 #include<unistd.h>14 #include<stdlib.h>15 #include<string.h>16 #include<pthread.h>*thread_function(void *arg);message[] = ;23 int num = 10; main()26 {27int res;28 pthread_t a_thread;29void *thread_result;30num = 10; 31 #ifdef CHAR32res = pthread_create(&a_thread, NULL, thread_function, (void *)message);res = pthread_create(&a_thread, NULL, thread_function, (void *)num);(res != 0)37 {);39 exit(EXIT_FAILURE);40 });43res = pthread_join(a_thread, &thread_result);44if (res != 0)45 {);47 exit(EXIT_FAILURE);48 }49 #ifdef CHAR, (char *)thread_result);, message);printf(, (int)thread_result);, num); exit(EXIT_SUCCESS);57 }*thread_function(void *arg)60 {61 #ifdef CHAR, (char *)arg);63sleep(3););); printf(, (int)arg);68sleep(3);69num = 100;}

View Code

需要注意的是:

1. 注释 line:65, 返回的是message的值”Bye”, 但是

2. 注释 line:70, 返回的是0, 而不是num的值

所以, 我们写线程函数的时候, 切记一定要调用pthread_exit((void*)value_ptr)退出.

,免备案空间,网站空间,网站空间伟人之所以伟大,是因为他与别人共处逆境时,

线程创建与销毁

相关文章:

你感兴趣的文章:

标签云: