ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

11 | 线程:如何让复杂的项目并行执行?

2019-11-24 18:01:54  阅读:196  来源: 互联网

标签:11 attr int void 并行执行 线程 pthread 进程


一、为什么要有线程 和 什么是线程?(why and waht)

1.概念:进程相当于一个项目,而线程就是为了完成项目需求,而建立的一个个开发任务。 2.为什么有进程还需线程  2.1资源问题 通信问题 执行问题
  • 进程只能在一个时间干一件事,如果想同时干两件事或多件事,进程就无能为力了。

  • 进程在执行的过程中如果阻塞,例如等待输入,整个进程就会挂起,即使进程中有些工作不依赖于输入的数据,也将无法执行。

二、如何创建线程?(how) 1 #include <pthread.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 #define NUM_OF_TASKS 5 6 7 void *downloadfile(void *filename) 8 { 9 printf("I am downloading the file %s!\n", (char *)filename); 10 sleep(10); 11 long downloadtime = rand()%100; 12 printf("I finish downloading the file within %d minutes!\n", downloadtime); 13 pthread_exit((void *)downloadtime); 14 } 15 16 int main(int argc, char *argv[]) 17 { 18 char files[NUM_OF_TASKS][20]={"file1.avi","file2.rmvb","file3.mp4","file4.wmv","file5 19 pthread_t threads[NUM_OF_TASKS]; 20 int rc; 21 int t; 22 int downloadtime; 23 24 pthread_attr_t thread_attr; 25 pthread_attr_init(&thread_attr); 26 pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_JOINABLE); 27 28 for(t=0;t<NUM_OF_TASKS;t++){ 29 printf("creating thread %d, please help me to download %s\n", t, files[t]); 30 rc = pthread_create(&threads[t], &thread_attr, downloadfile, (void *)files[t]); 31 if (rc){ 32 printf("ERROR; return code from pthread_create() is %d\n", rc); 33 exit(-1); 34 } 35 } 36 37 pthread_attr_destroy(&thread_attr); 38 39 for(t=0;t<NUM_OF_TASKS;t++){ 40 pthread_join(threads[t],(void**)&downloadtime); 41 printf("Thread %d downloads the file %s in %d minutes.\n",t,files[t],downloadtime) 42 } 43 44 pthread_exit(NULL);   三、线程特点(how) 线程数据 3.1 第一类是线程栈上的本地数据,比如函数执行过程中的局部变量。前面我们说过,函数的调 用会使用栈的模型,这在线程里面是一样的。只不过每个线程都有自己的栈空间。 3.2 第二类数据就是在整个进程里共享的全局数据。例如全局变量,虽然在不同进程中是隔离 的,但是在一个进程中是共享的。如果同一个全局变量,两个线程一起修改,那肯定会有问 题,有可能把数据改的面目全非。这就需要有一种机制来保护他们,锁机制。 3.3 这就是第三类数据,线程私有数据(Thread Specific Data), int pthread_setspecific(pthread_key_t key, const void *value) 设置私有数据值 void *pthread_getspecific(pthread_key_t key) 获取私有数据值 线程数据的保护 一种方式,Mutex,全称 Mutual Exclusion互斥锁 条件变量     总结

 

标签:11,attr,int,void,并行执行,线程,pthread,进程
来源: https://www.cnblogs.com/mzyc/p/11923389.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有