跟我一起做面试题-linux线程编程(1)

如题所述:

编写程序完成如下功能:

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 <string.h>
#include <pthread.h>
#include <errno.h>



int g_flag = 0;
pthread_cond_t cond_self_kill;
pthread_mutex_t m_kill;
pthread_mutex_t m_flag;



void *thread_child(void *arg)
{
	if(pthread_mutex_lock(&m_flag)!= 0)
	{
	    pthread_exit(NULL);
	}
    g_flag =(int)arg;
    printf("this is thread%d\n", (int)arg);
	if(pthread_mutex_unlock(&m_flag)!= 0)
	{
	    pthread_exit(NULL);
	}
    if((int)arg == 1)
    {
        if(pthread_cond_wait(&cond_self_kill, &m_kill) != 0)
        {
            pthread_exit(NULL);        
        }
        printf("thread%d exit\n", (int)arg);  
        
    }
    else
    {
        sleep(2);
        pthread_cond_broadcast(&cond_self_kill);
        printf("thread%d exit\n", (int)arg);  

    }
	pthread_exit(NULL);        

}


int main(int argc, char *argv[])
{

	pthread_t child[2];
	int ret;
	pthread_cond_init(&cond_self_kill, NULL);
	pthread_mutex_init(&m_flag, NULL);
	pthread_mutex_init(&m_kill, NULL);
	
	
    ret = pthread_create(&child[1], NULL, thread_child, (void*)2);
	if(ret)
	{
		return 1;
	}	
	ret = pthread_create(&child[0], NULL, thread_child, (void*)1);
	if(ret)
	{
		return 1;
	}	



    if(pthread_join(child[0], NULL) != 0)
    {
        pthread_join(child[1], NULL);
        return 1; 
    }
    pthread_join(child[1], NULL);
    printf("main thread exit\n");
    return 0;
}

 

 

转载于:https://www.cnblogs.com/boota/p/3942371.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值