zoukankan      html  css  js  c++  java
  • c++ 线程间通信方式

    一:两个进程间的两个线程通信,相当于进程间通信

    二:一个进程中的两个线程间通信

      通信方式:

    1.互斥锁

      mutex;

      lock_guard (在构造函数里加锁,在析构函数里解锁)

      unique_lock 自动加锁、解锁

    2.读写锁

      shared_lock

    3.信号量

      c++11中未实现,可以自己使用mutex和conditon_variable 实现

      代码实现如下:

        

    #pragma once
    #include <mutex>
    #include <condition_variable>
    class Semaphore
    {
    public:
     explicit Semaphore(unsigned int count); //用无符号数表示信号量资源 
     ~Semaphore();
    public:
     void wait();
     void signal();
    private:
     int m_count; //计数器必须是有符号数 
     std::mutex m_mutex;
     std::condition_variable m_condition_variable;
    };
     
    #include "Semaphore.h"
    Semaphore::Semaphore(unsigned int count) :m_count(count) {
    }
    Semaphore::~Semaphore()
    {
    }
    void Semaphore::wait() {
     std::unique_lock<std::mutex> unique_lock(m_mutex);
     --m_count;
     while (m_count < 0) {
      m_condition_variable.wait(unique_lock);
     }
    }
    void Semaphore::signal() {
     std::lock_guard<std::mutex> lg(m_mutex);
     if (++m_count < 1) {
      m_condition_variable.notify_one();
     }
    }

    4.条件变量

      condition_variable

  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/jobs1/p/10784021.html
Copyright © 2011-2022 走看看