操作系统 :多线程同步

 一、互斥锁

 在POSIX Thread中定义了一套专门用于线程同步的mutex函数。

1.创建和销毁

(1)有两种方法创建互斥锁,静态方法和动态方法

POSIX定义了一个宏PTHREAD_MUTEX_INITIALIZER来静态初始化互斥锁,方法如下

pthread_mutex_t  mutex=PTHREAD_MUTEX_INITIALIZER; 

在LinuxThreads实现中,pthread_mutex_t是一个结构,而

    PTHREAD_MUTEX_INITIALIZER是一个结构常量。

2、锁操作

锁操作主要包括加锁pthread_mutex_lock(),解锁pthread_mutex_unlock(),

锁不可能被两个不同的线程同时得到,必须等待解锁。在同一进程中的线程,如果加锁后没有

解锁,则任何其他线程都无法在获得锁。

 

intpthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t*mutex)

二、条件变量

1、 条件变量是利用在线程间共享的全局变量进行同步的一种机制,主要包括动作:一个线程等待“条件变量的成立”而挂起;

一个线程使“条件成立”

(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合起来。

1. 创建和注销

  条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:
pthread_cond_t cond=PTHREAD_COND_INITIALIZER

2. 等待和激发

intpthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)

无条件等待pthread_cond_wait()必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()的竞争条件。mutex互斥锁必须是普通锁或者适应锁,在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁。

激发条件:pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;

#include<stdlib.h>

#include<pthread.h>

#include<unistd.h>

intg_ flag=0;

staticpthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

staticpthread_cond_t cond=PTHREAD_COND_INITIALIZER;

void*thread1(void *argc)

{

    printf("this is thread1\n");

    pthread_mutex_lock(&mutex);

    if(g_flag==2)

        pthread_cond_signal(&cond);

    g_flag=1;

    pthread_mutex_unlock(&mutex);

    pthread_join(*(pthread_t*)argc,NULL);

    pthread_exit(0);

}

 

void*thread2(void *argc)

{

    printf("this is thread2\n");

    pthread_mutex_lock(&mutex);

    if(g_flag==1)

        pthread_cond_signal(&cond);

    g_flag=2;

    pthread_mutex_unlock(&mutex);

    pthread_exit(0);

}

 

intmain()

{

    printf("enter main\n");

    pthread_t tid1,tid2;

    int ret=0;

   if((ret=pthread_create(&tid1,NULL,thread1,&tid2))!=0)

        printf("create thread1error!\n");

   if((ret=pthread_create(&tid2,NULL,thread2,NULL))!=0)

        printf("create thread2error!\n");

    pthread_cond_wait(&cond,&mutex);

    printf("leave main\n");

    return 0;

}

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值