找回密码
 注册
搜索
查看: 1296|回复: 1

[讨论] Linux多线程同步方法

[复制链接]
发表于 2011-7-12 10:03:27 | 显示全部楼层 |阅读模式
作者:武汉华嵌嵌入式培训中心   讲师   张骏




       在线程对共享相同内存操作时,就会出现多个线程对同一资源的使用,为此,需要对这些线程进行同步,以确保它们在访问共享内存的时候不会访问到无效的数值。

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

#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);//创建线程
    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 <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 = %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);
}


更多技术文章敬请关注:武汉华嵌-嵌入式培训专家,国内领先的嵌入式服务机构,   
http://www.embedhq.org
http://www.embedhq.org
发表于 2011-7-13 22:32:42 | 显示全部楼层
very good,study and study
点评回复

使用道具 举报

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

Archiver|手机版|小黑屋|52RD我爱研发网 ( 沪ICP备2022007804号-2 )

GMT+8, 2024-10-9 07:23 , Processed in 0.044496 second(s), 16 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表