实验8线程及多线程间的互斥.docx

  1. 1、本文档共8页,可阅读全部内容。
  2. 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
实验8线程及多线程间的互斥

实验3 线程及多线程间的互斥实验目的:掌握线程API掌握多线程间的互斥掌握条件变量的使用方法实验要求:熟练使用该节所介绍线程间相关函数。实验器材:软件:1.安装了Ubunt的vmware虚拟机硬件:PC机一台实验步骤:练习线程的创建,传参,主线程回收资源,实验要求如下: 新建文件preadcreat.c,实现在主线程中创建一条创建线程,并给创建线程,传递字符串,在创建线程中打印退出,并将字符串的内容修改,在主线程中打印修改后的字符串。创建线程退出时给主线程传递参数。参考代码如下:掌握pthread_cancel函数的使用,编写pthreadcancel_ex.c,参考代码如下:#includestdio.h#includeunistd.h#includestdlib.h#includepthread.hvoid *thread_function(void *arg);int main(){int res;pthread_t a_thread;res =pthread_create(a_thread,NULL,thread_function,NULL);if(res!=0){perror(thread failed);exit(-1);}sleep(5);printf(cancelling thread....\n);res = pthread_cancel(a_thread);if(res!=0){perror(thread failed);exit(-1);}printf(wainting for thread\n);res = pthread_join(a_thread,NULL);if(res!=0){perror(thread join failed);exit(-1);}exit(0);}void *thread_function (void *arg){int i;for(i=0;i9;i++){printf(thread is running(%d)...\n,i); sleep(1);}pthread_exit(0);}掌握分离线程的创建方法,建立pthread_attr.c,参考代码如下:#include errno.h#include stdio.h#include unistd.h#include stdlib.h#include pthread.h#include string.h#include strings.hvoid *routine(void *arg){pthread_exit(NULL);}int main(void){pthread_attr_t attr;pthread_attr_init(attr);pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);/*** create a new thread with either** specified attributes nor arguments*/pthread_t tid;pthread_create(tid, attr, routine, NULL);errno = pthread_join(tid, NULL);if(errno == 0)printf(join thread successfully!\n);elseprintf(join thread failed: %s\n, strerror(errno));pthread_exit(NULL);}无名信号量实现线程间互斥,参考代码sem.c。阅读示例代码《pthreadmutex.c》,互斥锁的使用方法及逻辑。阅读示例代码《pthread_rwlock.c》,理解读写锁的逻辑。阅读示例代码《pthread_cond.c》,理解条件变量的逻辑。(选做题)阅读示例代码《pthread_cond_example》理解生产者与消费者模型。用双线程实现Jack 进程和Rose 进程,它们分别处理用户的键盘输入和收取对方的消息。思路:用任何一种IPC 进行进程间的数据传递(注意对临界资源访问的互斥性)线程总结:所有的线程库函数,成功一律返回0,失败一律返回errno如何避免僵尸线程:1,用pthread_join()来回收指定的僵尸线程的资源。2,将线程分离:pthread_setdetachstate()创建出来的线程,需要注意几点:1,他一定是跟别的线程是并发的,除非使用特殊的机制来同步他们。2,在访问临界资源(也就是各个线程共享的资源)的时候,一定互斥访问。3,缺省的新线程是可被接合的(也就是未分离的),退出的时候会变成僵尸。课后思考题:1) 阅读使用互斥锁和条件变量,线程池示例代码,理解线程池机制。2)并尝

文档评论(0)

haihang2017 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档