文章标题
来源:互联网 发布:大学排课软件 编辑:程序博客网 时间:2024/06/13 21:49
转自: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 是个泛型,传什么自己决定,传给回掉函数。
阅读全文
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- Python socket收发文件以及二进制文件打包
- RESTful 表单提交和ajax提交
- 大数据可视化第一天——前期准备
- sqlite的数据导入 导出
- 茂哥设计模式:简单工厂,工厂方法,抽象工厂
- 文章标题
- 后端URL中文传参+前端解析和页面显示
- 时间转换
- 公司招聘技术的技巧(程序员成长之路)
- 自定义alert弹出框
- HashMap类
- Linux IO模式及 select、poll、epoll详解
- vuex action mutation终于明白
- ThinkPHP