您的位置:首页 > 其它

线程间通信--线程创建与销毁

2013-07-25 10:27 302 查看
1. pthread_create(&a_thread, NULL, thread_function, (void *)message);
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: 创建成功返回的线程ID
attr:   线程属性, 该参数一般为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)指定传回. 但是还有一点疑问:


3. pthread_exit("Thank you for thr CPU time");
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()中最后一个参数的值.


/*******************************************************************************
* 版权所有:
* 模 块 名:
* 文 件 名:pthread1.c
* 实现功能:
* 作    者:XYZ
* 版    本:V1.0
* 日    期:2013.07.24
* 联系方式:xiao13149920@foxmail.com
********************************************************************************/
// This is pthread1.c pthread_create, pthread_join, pthread_exit
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>

//#define CHAR

void *thread_function(void *arg);

char message[] = "Hello world";
int num = 10;

int main()
{
int res;
pthread_t a_thread;
void *thread_result;
num = 10;
#ifdef  CHAR
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
#else
res = pthread_create(&a_thread, NULL, thread_function, (void *)num);
#endif
if (res != 0)
{
perror("Thread create failed");
exit(EXIT_FAILURE);
}

printf("Wating for thread to finsh...\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed");
exit(EXIT_FAILURE);
}
#ifdef CHAR
printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n", message);
#else
printf("Thread joined, it returned %d\n", (int)thread_result);
printf("num is now %d\n", num);
#endif
exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
#ifdef CHAR
printf("Thread_function is running. Argument was %s\n", (char *)arg);
sleep(3);
strcpy(message, "Bye!");
pthread_exit("Thank you for the CPU time");  // 注释该行,返回值是 “Bye“
#else
printf("Thread_function is running. Argument was %d\n", (int)arg);
sleep(3);
num = 100;
pthread_exit((void*)num);                        // 注释该行,返回值是 0
#endif
}


View Code
需要注意的是:

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

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

所以, 我们写线程函数的时候, 切记一定要调用pthread_exit((void*)value_ptr)退出.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: