润和面试题:开启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 
#include 
#include 

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);
        }
    }
}

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