线程同步 mutex

来源:互联网 发布:凤阳安广网络 编辑:程序博客网 时间:2024/06/06 19:34
#include<unistd.h>#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<semaphore.h>pthread_mutex_t mutex;char c[]="Hello world!\n";void function_a(){ int i; int len=strlen(c); //wiping working area   pthread_mutex_lock(&mutex);    printf("thread 1 gained access!\n"); for(i=0;i<len;i++) {   printf("%c",*(c+i) );   fflush(stdout);    sleep(1); } printf("\n");   pthread_mutex_unlock(&mutex);}void function_b(){ int i; int len=strlen(c); //wiping working area    pthread_mutex_lock(&mutex);    printf("thread 2 gained access!\n"); for(i=0;i<len;i++) {     c[i]='-';     fflush(stdout);     sleep(1); }     pthread_mutex_unlock(&mutex);}int main(){    int res;    res=pthread_mutex_init(&mutex,NULL);    if(res!=0)    {       printf("error: init mutex\n");       exit(EXIT_FAILURE);    }    pthread_t thd1,thd2;    res=pthread_create(&thd1,NULL,function_a,NULL);    if(res!=0)    {       printf("error: create thread\n");       exit(EXIT_FAILURE);    }    res=pthread_create(&thd2,NULL,function_b,NULL);    if(res!=0)    {       printf("error: create thread\n");       exit(EXIT_FAILURE);    }    res=pthread_join(thd1,NULL);    if(res!=0)    {       printf("error: create thread\n");       exit(EXIT_FAILURE);    }    res=pthread_join(thd2,NULL);    if(res!=0)    {       printf("error: create thread\n");       exit(EXIT_FAILURE);    }    printf("thread joined, now exit....\n");    pthread_mutex_destroy(&mutex);    return 0;}


线程1,2抢占内存c。

若线程1首先抢占成功则输出Helloworld。

若线程2首先抢占成功则输出---------------。

由于使用了mutex,不会输出H-ll-wo-ld。这样的乱码。

0 0
原创粉丝点击