初探互斥量

1.互斥量的概念前面已经提及

2.一个demo

要求 四个线程,每个线程分别输出a b c d,是拼命输出,如何让他们在终端上输出顺序的a b c d

pthread_mutex_t mut[THRNUM];


void * Fun(void *p)
{
    
    
        int c = 'a' + (int)p;
        int i = (int)p;
        int next = (i+1)%THRNUM;

        while(1)
        {
    
    
                pthread_mutex_lock(mut+i);

                write(1, &c, 1);

                pthread_mutex_unlock(mut+next);


        }
        pthread_exit(NULL);
}

int main()
{
    
    
        pthread_t tid[THRNUM];
        int i,err;

        for(i = 0 ; i <= THRNUM; i++)
        {
    
    
                pthread_mutex_init(mut+i, NULL);
                pthread_mutex_lock(mut+i);

                err = pthread_create(tid+i, NULL, Fun, (void *)i);
                if(err)
                {
    
    
                        fprintf(stderr, "create()%s ", strerror(err));
                        exit(1);
                }

        }

        pthread_mutex_unlock(mut+0);

        alarm(1);

        for(i = 0; i <= THRNUM; i++)
        {
    
    
                pthread_join(tid[i], NULL);

        }

        for(i = 0; i <= THRNUM; i++)
                pthread_mutex_destroy(mut+i);

        return 0;
}

我们在每创建一个线程的时候,先把其锁住,然后每个线程获取一个锁,再次阻塞,我们在main线程中打开了a的锁,然后a写入完成后,他打开b的锁,b可以运行,然后再打开c的锁,一次类推

猜你喜欢

转载自blog.csdn.net/ZZHinclude/article/details/119653343