线程同步API

目录

原生

线程

#include<pthread.h>
pthread_t pthread_self()//打印线程id;
int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *), void *arg);
pthread_exit();//退出线程
pthread_join(pthread_t thread, void **retval);//retval线程返回值
pthread_detach(pthread_t thread);
pthread_cancel(pthread_t thread);//杀死线程

互斥量

#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_init(&mutex,NULL);
pthread_mutex_lock(&mutex)
pthread_cond_wait(&cond,&mutex)
pthread_mutex_unlock(&mutex)

条件变量

#include <unistd.h>
#include <pthread.h>
pthread_cond_t cond
pthread_cond_init(&cond,NULL);
pthread_cond_wait(&cond,&mutex)
pthread_cond_signal(&cond); //唤醒至少一个线程
pthread_cond_broadcast(&cond);//唤醒所有线程

struct timespec time;
time.tv_nsec = 0;
time.tv_sec = 10;
pthread_cond_timedwait(&cond, &mutex, &time);

pthread_cond_destroy(&cond)

信号量

#include<semaphore.h>
sem_t sem;
int sem_init(sem_t* sem,int pshared,unsigned int value);
       pshared:0线程同步  1进程同步
       value:互斥量初始值
sem_wait(&sem);// --
sem_post(&sem);// ++
sem_timedwait(sem_t * sem, const timespec *_time);
sem_destroy(&sem);

C++11

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cond;
int sum = 0;
void producer()
{
    cout << this_thread::get_id() << endl;
    for (int i = 0; i < 100; i++)
    {
        unique_lock<mutex> lock(mtx);
        cond.wait(lock, []() // 等待可以生产
                  { return sum == 0; });
        sum++;
        cout << "生产者" << i << endl;
        cond.notify_one();
    }
}
void comsumer()
{
    cout << this_thread::get_id() << endl;
    for (int i = 0; i < 100; i++)
    {
        unique_lock<mutex> lock(mtx);
        cond.wait(lock, [=]() // 等待可以消费
                  { return sum == 1; });

        sum--;
        cout << "消费者" << i << endl;
        cond.notify_one();
    }
}
int main()
{
    thread t1(producer);
    thread t2(comsumer);
    t1.join();
    t2.join();
    cout << sum;
    return 0;
}

wait一段时间

cond.wait_for(lock, std::chrono::seconds(3), []()
                      { return sum != 1; });

注意:wait(mutex,谓词条件)
条件满足:不阻塞,直接向下执行
条件不满足:释放锁,阻塞,等待唤醒
被唤醒:获取锁,检查条件,不满足条件继续释放锁阻塞。满足条件程序继续执行

线程的虚唤醒:指的是多个线程阻塞在同一个信号量,当使用notify_all()的时候所有线程都会被唤醒,但大部分线程条件谓词仍不满足,需要继续阻塞,这就是虚唤醒

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值