多线程并行与退出
来源:互联网 发布:火车时刻表软件 编辑:程序博客网 时间:2024/06/02 00:22
例1:进程与线程并行输出
#include <stdio.h>#include <string.h>#include <errno.h>#include <pthread.h>//线程函数入口void *thread_routine(void *arg){printf("I am a thread, my thread id is : %d\n", pthread_self()); int i;for ( i = 0; i < 5; i++){printf("thread i = %d\n", i);fflush(stdout); //冲洗缓冲区,避免影响进程sleep(1);}printf("I am a thread, I will exit\n");}int main(){pthread_t tid;int ret = 0;ret = pthread_create(&tid, NULL, thread_routine, NULL); //创建一个线程if (ret != 0){printf("pthread_create error\n");exit(0);} int i;for ( i = 0; i < 5; i++){printf("main i = %d\n", i);fflush(stdout); //冲洗缓冲区,避免影响线程sleep(1);}sleep(2); //等待线程退出,如果线程还在执行,但是进程退出,那么线程也会退出printf("parent exit\n");exit(0);}
例2:等待线程与线程退出函数
#include <stdio.h>#include <string.h>#include <errno.h>#include <pthread.h>//线程函数入口void *thread_routine(void *arg){printf("I am a thread, my thread id is : %d\n", pthread_self());int i;for (i = 0; i < 5; i++){printf("thread i = %d\n", i);fflush(stdout); //冲洗缓冲区,避免影响进程sleep(1);}sleep(3);printf("child exit\n");pthread_exit(NULL);//线程结束函数}int main(){pthread_t tid;int ret = 0;ret = pthread_create(&tid, NULL, thread_routine, NULL); //创建一个线程if (ret != 0){printf("pthread_create error\n");exit(0);}int i;for (i = 0; i < 5; i++){printf("main i = %d\n", i);fflush(stdout); //冲洗缓冲区,避免影响线程sleep(1);}pthread_join(tid, NULL);//等待线程退出printf("parent exit\n");exit(0);}
例3:创建多个线程,并向线程传递数据
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <errno.h>#include <pthread.h>typedef struct Threadinfo{char name[64];int age;int numId;}ThreadInfo;int nNum, nLoop;void *thread_routine(void *arg){int i = 0;ThreadInfo * p = (ThreadInfo*)arg;for (i = 0; i < nLoop; ++i){printf("thread id is : %d, numid is %d\n", pthread_self(), i, p->numId);}printf("child exit: %d\n", pthread_self());pthread_exit(arg);}int main(){int i = 0;pthread_t tidArray[200];ThreadInfo tmp[200];printf("Input the number of thread:");scanf("%d", &nNum);printf("Input the number of nLoop:");scanf("%d", &nLoop);int ret = 0;for (i = 0; i < nNum; ++i){memset(&tmp[i], 0, sizeof(ThreadInfo));tmp[i].numId = i;pthread_create(&tidArray[i], NULL, thread_routine, &tmp[i]);}for (i = 0; i < nNum; ++i){pthread_join(tidArray[i], NULL);}printf("parent exit\n");exit(0);}
阅读全文
0 0
- 多线程并行与退出
- java 并行与多线程区别
- Python-多线程与并行计算
- 信号量与多线程的退出
- 浅谈多核CPU、多线程与并行计算
- 浅谈多核CPU、多线程与并行计算
- 浅谈多核CPU、多线程与并行计算
- C#中的并行与多线程编程
- C#中的并行与多线程编程
- Python 多线程教程:并发与并行
- 多线程 ---并发与并行概念总结
- 浅谈多核CPU、多线程与并行计算
- 浅谈多核CPU、多线程与并行计算
- Python 多线程教程:并发与并行
- 并发和并行,异步与多线程区别
- 多线程 ---并发与并行概念总结
- C#中的并行与多线程编程
- 多线程 ---并发与并行概念总结
- mysql数据库常用操作
- MVP架构模式
- element UI+七牛云快速搭建图片服务器
- 新知识杂记-2017/5/17
- 分形理论入门
- 多线程并行与退出
- KVC KVO 高阶应用
- 栈的基本操作
- 公共技术点之 View 事件传递
- CodeForces
- 给定先序和后续,构造出一颗二叉树并输出中序序列
- Python数据结构—-栈
- 使用对象流把对象保存到文本中
- 使用DevExpress的PdfViewer控件加载http传输文件