【线程】linux之多线程同步互斥技术

 

1.同步机制

 

   线程同步机制主要有:互斥量/信号量/条件变量/读写锁等。


2.技术示例

 

   创建2个计数线程A和B,每次计数加1,当为偶数时,A线程计数;当为奇数时,B线程计数。

   源码:
//thread_mutex_cond.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define MAX_COUNT9
pthread_mutex_t mutex;
pthread_cond_t cond;
int count=0;
void AddCount_Odd_Func(void);
void AddCount_Even_Func(void);
int main()
{
    int ret;
    pthread_t odd_thread,even_thread;
    pthread_attr_t thread_attr;
    count = 0;
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    ret = pthread_attr_init(&thread_attr);
    if (ret != 0)
    {
        perror("Attribute Creation Failed");
        exit(EXIT_FAILURE);
    }
    pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);
                                                     
    ret=pthread_create(&odd_thread,&thread_attr,(void *)&AddCount_Odd_Func,NULL);
    if(ret != 0)
    {
        perror("Thread Creation Failed");
        exit(EXIT_FAILURE);
    }
    ret = pthread_create(&even_thread,&thread_attr,(void *)&AddCount_Even_Func, NULL);
    if (ret != 0)
    {
        perror("Thread Creation Failed");
        exit(EXIT_FAILURE);
    }
    while(count<MAX_COUNT); 
    printf("Finished!\n");
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    return 0;
}
void AddCount_Odd_Func(void)
{
    pthread_mutex_lock(&mutex);
    while(count<MAX_COUNT)
    {
        if(count%2==1)
        {
            count++;
            printf("AddCount_Odd_Func():count=%d.\n",count);
            pthread_cond_signal(&cond);
        }
        else
            pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);
}
void AddCount_Even_Func(void)
{
    pthread_mutex_lock(&mutex);
    while(count<MAX_COUNT)
    {
        if(count%2==0)
        {
            count++;
            printf("AddCount_Even_Func():count=%d.\n",count);
            pthread_cond_signal(&cond);
        }
        else
            pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);
}
View Code

 


3.mystery注解

 

   1)示例中,创建了互斥量mutex与条件量cond。mutex用于互斥操作,cond用于在相关条件成立时进行操作

   2)pthread_attr_setdetachstate()函数设置线程为分离状态
   3)pthread_cond_wait()使线程阻塞
   4)pthread_cond_broadcast()函数用来唤醒所有被阻塞在条件变量cond上的线程。
       要注意,被唤醒后的这些线程将再次竞争相应的互斥量
   5)pthread_cond_init()函数创建条件变量

   6)pthread_cond_signal()函数用来释放被阻塞在条件变量cond上的线程

 

你可能感兴趣的:(linux)