一:兩個進程間的兩個線程通訊,至關於進程間通訊c++
二:一個進程中的兩個線程間通訊函數
通訊方式:線程
1.互斥鎖c++11
mutex;code
lock_guard (在構造函數里加鎖,在析構函數裏解鎖)進程
unique_lock
自動加鎖、解鎖ci
2.讀寫鎖資源
shared_lock
it
3.信號量io
c++11中未實現,能夠本身使用mutex和conditon_variable 實現
代碼實現以下:
#pragma once
#include <mutex>
#include <condition_variable>
class Semaphore
{
public:
explicit Semaphore(unsigned int count); //用無符號數表示信號量資源
~Semaphore();
#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;
};
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);
}
}
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();
}
}
std::lock_guard<std::mutex> lg(m_mutex);
if (++m_count < 1) {
m_condition_variable.notify_one();
}
}
4.條件變量
condition_variable