使用互斥量实现多线程交替打印helloworld

/*===============================================================
*  Copyright(C) 2020 Burgess Fan aLL rights reserved.
*  
*  文件名称:mutex.c
*   创 建 者:Burgess
*   创建日期:2020年05月10日
================================================================*/
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int sum=0;

void* thr1(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);//加锁
        printf("I am thread No1,hello world!
");
        sleep(1);
        pthread_mutex_unlock(&mutex);//释放锁
        sleep(1);//增加睡眠时间确保不会让线程本身抢到锁
    }
}

void* thr2(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        printf("I am thread No2,HELLO  WORLD!
");
        sleep(1);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

int main()
{
    pthread_t tid[2];
    pthread_create(&tid[0],NULL,thr1,NULL);
    pthread_create(&tid[1],NULL,thr2,NULL);
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
    return 0;
}

原文地址:https://www.cnblogs.com/Burgess-Fan/p/12862755.html