润和面试题:开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。

编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co.,     Ltd. 
File name:
Author:Jerey_Jobs    Version:0.1    Date: 
Description:
Funcion List: 
*****************************************************/

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

int flag = 1;
int n = 0;
pthread_mutex_t mutex;

void fun_thread(char *msg);

int main()
{
    pthread_t thread;
    int val;
    int i;

    if(pthread_mutex_init(&mutex,NULL) != 0)
    {
        printf("init mutex error\n");
        exit(1);
    }

    if(pthread_create(&thread,NULL,(void *)fun_thread,NULL) != 0)
    {
        printf("create thread error\n");
        exit(1);
    }

    while(1)
    {
        if(flag == 0)
        {
            val = pthread_mutex_lock(&mutex);

            if(val != 0)
            {
                printf("main thread lock error\n");
                exit(1);
            }

            printf("main thread has locked\n");

            for(i = 0;i < 6;i++)
            {
                printf("main thread is working    %d times\n",i);
            }

            flag = 1;

            printf("main thread unocked\n");
            pthread_mutex_unlock(&mutex);
        }
    /*  if(n == 5)
            exit(1);*/
        if(n == 5)
            break;
    }

    return 0;
}

void fun_thread(char *msg)
{
    int val;
    int i;

    while(n < 5)
    {
        if(flag == 1)
        {
            val = pthread_mutex_lock(&mutex);

            if(val != 0)
            {
                printf("thread lock error\n");
                exit(1);
            }

            printf("thread has locked\n");

            for(i = 0;i < 3;i++)
            {
                printf("thread is working   %d times\n",i);
            }

            flag = 0;

            printf("thread is unlocked\n");

            n++;

        printf("*****************************************%d\n",n);
            pthread_mutex_unlock(&mutex);
        }
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值