linux 互斥锁

#include <assert.h>

#include <errno.h>

#include <stdio.h>

#include <stdlib.h>

#include <time.h>



#include <pthread.h>



#define __FUNC__ __func__



pthread_mutex_t hMutex = PTHREAD_MUTEX_INITIALIZER;

void *

threadFunc1(void *arg)

{



        while(1)

        {

                pthread_mutex_lock(&hMutex);

                sleep(10);

                (void)printf("%s:%d:%s\n", __FILE__, __LINE__, __FUNC__);

                pthread_mutex_unlock(&hMutex);

                pthread_yield();

        }

        return 0;

}



void *

threadFunc2(void *arg)

{



        while(1)

        {

                pthread_mutex_lock(&hMutex);

                sleep(5);

                (void)printf("%s:%d:%s\n", __FILE__, __LINE__, __FUNC__);

                pthread_mutex_unlock(&hMutex);

                pthread_yield();

        }

        return 0;

}

int main(void)

{

        pthread_t tid1, tid2;



        pthread_setconcurrency(3);

        pthread_create(&tid1, NULL, threadFunc1, NULL);

        pthread_create(&tid2, NULL, threadFunc2, NULL);



        pause();

        return 0;

}



用pthread_yield();
函数实现让出 线程控制权;也可以用nanosleep来代替sleep 减小休眠时间

你可能感兴趣的:(linux)