多线程同步

来源:互联网 发布:mysql 先排序后去重 编辑:程序博客网 时间:2024/05/16 05:26
</pre><p>一、互斥锁</p><p><pre name="code" class="cpp">#include<stdio.h>#include<pthread.h>#include<stdlib.h>#include<unistd.h>int globle_i = 50;pthread_mutex_t globle_mutex;void* thread_func(){  // pthread_mutex_lock(&globle_mutex);  //如果不加锁,仍然可以改变globel_i,所以需要自己控制好锁   while(globle_i != 0)    {        if( globle_i != 0)          {            globle_i  = globle_i  -1;         }        printf("in new thread globle_i = %d\n", globle_i);        usleep(1);    }   //pthread_mutex_unlock(&globle_mutex);    return NULL;}int main(){   pthread_t thread;   int res = -1;   res = pthread_mutex_init(&globle_mutex, NULL);   if(res != 0){        perror("ptherad_mutex_init failed!\n");         exit(EXIT_FAILURE);   }       res = pthread_create(&thread, NULL, thread_func, NULL);   if(res != 0)   {        perror("ptherad_mutex_init failed!\n");         exit(EXIT_FAILURE);   }   pthread_mutex_lock(&globle_mutex);   while(globle_i != 0)    {        if( globle_i != 0)          {            globle_i  = globle_i  -1;         }        else{            printf("no more\n");         }        printf("in the main thread globle_i=%d\n", globle_i);        usleep(1);    }   pthread_mutex_unlock(&globle_mutex);   res = pthread_join(thread, NULL);   if(res != 0)   {       perror("pthread_join failed\n");        exit(EXIT_FAILURE);   }   printf("thread joined\n");   pthread_mutex_destroy(&globle_mutex);    return 0;}

二、条件变量


三、信号量


0 0
原创粉丝点击