心心程序博客

眼过千遍不如手过一遍! 书看千行不如手敲一行! 手敲千行不如单步一行! 单步源代码千行不如单步对应汇编一行!

导航

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 减小休眠时间

posted on 2012-04-23 09:24  心心程序博客  阅读(2991)  评论(0编辑  收藏  举报