Chinaunix首页 | 论坛 | 博客
  • 博客访问: 479447
  • 博文数量: 130
  • 博客积分: 2111
  • 博客等级: 大尉
  • 技术积分: 1373
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-28 09:55
个人简介

IT民工

文章分类

全部博文(130)

文章存档

2021年(1)

2019年(1)

2017年(3)

2014年(1)

2013年(3)

2012年(2)

2011年(3)

2010年(2)

2009年(114)

分类: LINUX

2009-09-01 13:21:04

linux多线程编程
2008-07-14 13:11:54

/*
 *  一个简单的linux 多线程编程实例,源码来自网络
 */

#include
#include
#include
#include

#define MAX 2
pthread_t thread[2];
pthread_mutex_t mut;

int number=0, i;


void *thread1(void)
{
 printf("thread1 : I`m thread 1 \n");
 for (i=0; i {
  printf("thread1 : number %d \n",number);
  pthread_mutex_lock(&mut);   // 上锁
  number++;
  pthread_mutex_unlock(&mut);   // 解锁
  sleep(1);
 }
 printf("thread1: 主函数在等我完成任务吗? \n");
 pthread_exit(NULL);
}


void *thread2(void)
{
 printf("thread2: I`m thread2 \n");
 for (i=0; i {
  printf("thread2: number = %d \n",number);
  pthread_mutex_lock(&mut);
  number++;
  pthread_mutex_unlock(&mut);
  sleep(1);
 }
 printf("thread2:  主函数在等我完成任务吗? \n");
 pthread_exit(NULL); // 结束线程
}


void thread_create(void)
{
 int tmp;


 memset(&thread,0,sizeof(thread));
 if((tmp = pthread_create(&thread[0],NULL,(void *)thread1,NULL)) != 0) // 创建线程,返回0创建成功
 {
  printf("线程 1 创建失败 \n");
 }
 else
 {
  printf(" 线程 1 创建成功! \n");
 }

 if ((tmp = pthread_create(&thread[1],NULL,(void *)thread2,NULL)) != 0)
 {
  printf("线程 2 创建失败 \n");
 }
 else
 {
  printf("线程 2 创建成功 !\n");
 }
}

void thread_wait(void)
{
 void *o1,*o2;
 if (thread[0] != 0)
 {
  pthread_join(thread[0],NULL); // 等待线程结束
  printf("线程 1 已经结束 \n");
 }
 if (thread[1] != 0)
 {
  pthread_join(thread[1],NULL);
  printf("线程 2 已经结束 \n");
 }
}


int main()
{
 pthread_mutex_init(&mut,NULL);  //生成互斥锁
 printf("我是主函数,我正在创建线程 ! \n");
 thread_create();
 printf("主函数:等待线程完成任务 ! \n");
 thread_wait();
 printf("主函数:退出! byebye !\n");

 return 0;
}

阅读(445) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~