最基本的linux线程编写和锁的使用

/*
  熟悉POSIX多线程编程技术?完成如下功能:
  1)有一int型全局变量g_Flag初始值为0;
  2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
  3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
  4)线程序1需要在线程2退出后才能退出
  5)主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出
   */


#include <stdio.h>

#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>

int g_flag = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* thread1(void*);
void* thread2(void*);

int main(int argc,char** argv)
{
printf("enter main\n");
pthread_t tid1,tid2;
int ret1 = 0 , ret2 = 0;

ret2 = pthread_create(&tid2,NULL,thread2,NULL);
if(ret2 != 0 )
printf("%s:%d\n",__func__,strerror(ret2));

ret1 = pthread_create(&tid1,NULL,thread1,&tid2);
if(ret1 != 0)
printf("%s:%d\n",__func__,strerror(ret1));

printf("leave main\n");
pthread_cond_wait(&cond,&mutex);

return 0 ;
}
 


void* thread1(void* arg)
{
pthread_t tid2 = *(pthread_t *)arg;

printf("thread1flag:%d \n",g_flag );

pthread_mutex_lock(&mutex);
if(g_flag == 2)
pthread_cond_signal(&cond);
g_flag = 1;
pthread_mutex_unlock(&mutex);
printf("thread1flag:%d\n",g_flag);
        pthread_join(tid2,NULL);
pthread_exit(0);
}

void* thread2(void* arg)
{
printf("thread2flag:%d\n",g_flag);
pthread_mutex_lock(&mutex);
if(g_flag == 1)
pthread_cond_signal(&cond);
g_flag = 2;
pthread_mutex_unlock(&mutex);
printf("thread2flag:%d\n",g_flag);
pthread_exit(0);

}


参考:http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值