欢迎登陆真网站,您的到来是我们的荣幸。 登陆 注册 忘记密码? ☆设为首页 △加入收藏
欢迎加入真幸福QQ群
电脑知识: 基础知识 网络技术 操作系统 办公软件 电脑维修 电脑安全 windows7 windows8 windows10 服务器教程 平板电脑 视频播放教程 网络应用 互联网 工具软件 浏览器教程 QQ技巧 输入法教程 影视制作 YY教程 wps教程 word教程 Excel教程 PowerPoint
云南西双版纳特产小花糯玉米真空包装


MAC解决Spotlight 的‘索引中问题
mac操作系统sudo的时候不用输入密码
XP中根据端口号或PID查看进程
2004无法打开服务器服务。服务器性能数据将不会被返回
DM硬盘分区使用教程
win客户端和linux客户端的区别
unix/linux内核在系统里扮演什么
Linux如何清空所有iptables规则
快速扫除windows注册表垃圾的方案
CentOS Linux解决网卡启动时候报Device eth0 does not seem to
Linux多线程编程
【 来源:网络 】【 点击:1 】 【 发布时间:2017_03_03 08:59:59 】

   #include

  #include

  #include

  #include

  #define MAX 10

  pthread_t thread[2];

  pthread_mutex_t mut;

  int number=0, i;

  void *thread1()

  {

  printf ("thread1 : I'm thread 1n");

  for (i = 0; i < MAX; i++)

  {

  printf("thread1 : number = %dn",number);

  pthread_mutex_lock(&mut);

  number++;

  pthread_mutex_unlock(&mut);

  sleep(2);

  }

  printf("thread1 :主函数在等我完成任务吗?n");

  pthread_exit(NULL);

  }

  void *thread2()

  {

  printf("thread2 : I'm thread 2n");

  for (i = 0; i < MAX; i++)

  {

  printf("thread2 : number = %dn",number);

  pthread_mutex_lock(&mut);

  number++;

  pthread_mutex_unlock(&mut);

  sleep(3);

  }

  printf("thread2 :主函数在等我完成任务吗?n");

  pthread_exit(NULL);

  }

  void thread_create(void)

  {

  int temp;

  memset(&thread, 0, sizeof(thread)); //comment1

  /*创建线程*/

  if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2

  printf("线程1创建失败!n");

  else

  printf("线程1被创建n");

  if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3

  printf("线程2创建失败");

  else

  printf("线程2被创建n");

  }

  void thread_wait(void)

  {

  /*等待线程结束*/

  if(thread[0] !=0) { //comment4

  pthread_join(thread[0],NULL);

  printf("线程1已经结束n");

  }

  if(thread[1] !=0) { //comment5

  pthread_join(thread[1],NULL);

  printf("线程2已经结束n");

  }

  }

  int main()

  {

  /*用默认属性初始化互斥锁*/

  pthread_mutex_init(&mut,NULL);

  printf("我是主函数哦,我正在创建线程,呵呵n");

  thread_create();

  printf("我是主函数哦,我正在等待线程完成任务阿,呵呵n");

  thread_wait();

  return 0;

  }

本网站由川南居提供技术支持,fkzxf版权所有 浙ICP备12031891号
淳安分站 淳安分站