您的位置:首页 > 其它

文章标题

2017-07-21 10:03 218 查看
转自:http://www.cnblogs.com/kuliuheng/p/4062941.html

test1.c

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *thread_function(void *arg);
void *thread_function1(void *arg);
char message[] = "Hello World";
int abc[2] = {10,12};
int main()
{
int res;
pthread_t a_thread[2];
pthread_t *s;
void *thread_result;
s = a_thread;
res = pthread_create(s, NULL, thread_function, (void *)message);
s++;
pthread_create(s, NULL, thread_function1, (void *)&abc[0]);
if (res != 0)
{
perror("Thread creation failed!");
exit(EXIT_FAILURE);
}

printf("Waiting for thread to finish...\n");

res = pthread_join(a_thread[0], &thread_result);
pthread_join(a_thread[1], NULL);
if (res != 0)
{
perror("Thread join failed!\n");
exit(EXIT_FAILURE);
}

printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n", message);

exit(EXIT_FAILURE);
}

void *thread_function(void *arg)
{
printf("thread_function0 of Argument was %s\n", (char *)arg);
sleep(3);
strcpy(message, "Bye00");
pthread_exit("Thank you for your CPU time\n");
}

void *thread_function1(void *arg)
{
int a = *(int *)arg;
printf("thread_function1 of Argument was %d\n", a);
sleep(6);
strcpy(message, "Bye11");
pthread_exit("Thank you for your CPU time\n");
}


编译:gcc -o test1 test1.c -D REENTRANT -lpthread

运行结果:



1.pthread_join函数中的线程函数分别运行,而printf(“Thread joined, it returned %s\n”, (char *)thread_result);则需要pthread_join加入的线程内函数全部完成后才执行,所以打印“Thread joined, it returned”需要等待大约6s后。

2.传递参数,可以看到pthread_create(s, NULL, thread_function1, (void )&abc[0]);中(void )arg 是个泛型,传什么自己决定,传给回掉函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程