日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當(dāng)前位置:首頁 > 嵌入式 > 嵌入式教程
[導(dǎo)讀]Linux多線程同步方法

以下是線程的幾種同步方式:

1、 互斥量。

通過使用pthread的互斥接口保護(hù)數(shù)據(jù),確保同一時(shí)間只有一個(gè)線程訪問數(shù)據(jù)?;コ饬繌谋举|(zhì)上講是一把鎖,在訪問共享資源前對互斥量進(jìn)行加鎖,在訪問完成后釋放互斥量上的鎖。如下例所示,就是互斥量對共享數(shù)據(jù)的操作:

#include <stdio.h>
#include <pthread.h>
int value = 5;//共享變量
pthread_mutex_t mutex;//互斥變量
void *mythread1();
void mainshow();
int main()
{
    int retval;
    pthread_t tid1;
    retval = pthread_create(&tid1,NULL,mythread1,&value);//創(chuàng)建線程
    if(retval != 0){printf(“Can not create mythread1n”);
    mainshow();
    retval = pthread_join(&tid1,NULL);//等待線程mythread1結(jié)束
    if(retval != 0){printf(“Can not join with mythread.n”);
    printf(“value = %dn”,value);
    return 0;
}

void *mythread1()
{
      int retval;
      retval = pthread_mutex_lock(&mutex);//上鎖
      value = value + 1;//對共享變量的操作
      printf("value = %dn",value);
      retval = pthread_mutex_unlock(&mutex);//解鎖
      pthread_exit((void *)0);
}


void myshow()
{
      int retval;
      retval = pthread_mutex_lock(&mutex);//上鎖
      value = value + 1;//對共享變量的操作
      printf(“value = %dn”,value);
      pthread_mutex_unlock(&mutex);//解鎖
}

2、信號量

該信號量是Posix提供的基于內(nèi)存的信號量,它們由應(yīng)用程序分配信號量的內(nèi)存空間。如下例所示,就是信號量對共享數(shù)據(jù)的操作:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int value = 5;
sem_t sem1,sem2;
void mainshow();
void *mythread();
int main()
{
       int retval;
       pthread_t tid;
       retval = sem_init(&sem1,0,0);
       retval = sem_init(&sem2,0,1);
       retval =pthread_create(&tid,NULL,mythread,NULL);
       mainshow();
       pthread_join(tid,NULL);


       printf("value3 = %dn",value);
       return 0;
}


void *mythread()
{
       int retval;
       retval = sem_wait(&sem1);
       value = value + 1;
       printf("value1 = %dn",value);
       retval = sem_post(&sem2);
       pthread_exit((void *) 0);
}


void mainshow()
{
       int retval;
       retval = sem_wait(&sem2);
       value = value + 1;
       printf("value2 = %dn",value);
       retval = sem_post(&sem1);
}
 

本站聲明: 本文章由作者或相關(guān)機(jī)構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點(diǎn),本站亦不保證或承諾內(nèi)容真實(shí)性等。需要轉(zhuǎn)載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請及時(shí)聯(lián)系本站刪除( 郵箱:macysun@21ic.com )。
換一批
延伸閱讀
關(guān)閉