Linux多线程同步方法

Linux多线程同步方法,第1张

以下是线程的几种同步方式:

1、 互斥量。

通过使用pthread的互斥接口保护数据,确保同一时间只有一个线程访问数据。互斥量从本质上讲是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。如下例所示,就是互斥量对共享数据的 *** 作:

#include
#include
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);//创建线程
    if(retval != 0){printf(“Can not create mythread1\n”);
    mainshow();
    retval = pthread_join(&TId1,NULL);//等待线程mythread1结束
    if(retval != 0){printf(“Can not join with mythread.\n”);
    printf(“value = %d\n”,value);
    return 0;
}

void *mythread1()
{
      int retval;
      retval = pthread_mutex_lock(&mutex);//上锁
      value = value + 1;//对共享变量的 *** 作
      printf("value = %d\n",value);
      retval = pthread_mutex_unlock(&mutex);//解锁
      pthread_exit((void *)0);
}


void myshow()
{
      int retval;
      retval = pthread_mutex_lock(&mutex);//上锁
      value = value + 1;//对共享变量的 *** 作
      printf(“value = %d\n”,value);
      pthread_mutex_unlock(&mutex);//解锁
}

2、信号量

该信号量是Posix提供的基于内存的信号量,它们由应用程序分配信号量的内存空间。如下例所示,就是信号量对共享数据的 *** 作:

#include
#include
#include
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 = %d\n",value);
       return 0;
}


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


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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/dianzi/2713476.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-08-17
下一篇 2022-08-17

发表评论

登录后才能评论

评论列表(0条)

保存