信号量并发:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <queue>
#include <semaphore.h>
#include <unistd.h>
#include <memory>
#include <mutex>
#include <condition_variable>
using namespace std;
pthread_mutex_t m_queue_lock;
pthread_cond_t m_cond;;
condition_variable cond;
mutex mu;
mutex mu1;
int wakeups = 0;
void* thread_func(void* _pool) {
cout << *((int*)_pool) << " seq " << endl;
while(1) {
std::unique_lock<std::mutex> lock(mu);
cond.wait(lock, [&]()->bool{ return wakeups>0;});
int v = wakeups--;
cout << *((int*)_pool) << " hello " << v << endl;
}
}
void* thread_func1(void* _pool) {
cout << *((int*)_pool) << " seq " << endl;
while(1) {
int v = 0;
{
std::unique_lock<std::mutex> lock(mu);
cond.wait(lock, [&]()->bool{ return wakeups >0;});
v = wakeups--;
}
sleep(5);
{
std::unique_lock<std::mutex> lock(mu1);
cout << *((int*)_pool) << " hello " << v << endl;
}
sleep(5);
}
}
void* thread_func2(void* _pool) {
cout << *((int*)_pool) << " seq " << endl;
while(1) {
pthread_mutex_lock(&m_queue_lock);
pthread_cond_wait(&m_cond, &m_queue_lock);
pthread_mutex_unlock(&m_queue_lock);
sleep(5);
cout << *((int*)_pool) << " hello" << endl;
sleep(5);
}
}
int main() {
pthread_mutex_init(&m_queue_lock, NULL);
pthread_cond_init(&m_cond, NULL);
pthread_t* m_pids = new pthread_t[100];
for (int i = 0; i < 10; ++i) {
pthread_create(&m_pids[i], NULL, &thread_func1, &i);
}
sleep(2);
cout << "begin" << endl;
{
//std::lock_guard<std::mutex> lock(mu);
wakeups = 100;
//cond.notify_one();
cond.notify_all();
}
/*
{
//pthread_mutex_lock(&m_queue_lock);
pthread_cond_broadcast(&m_cond);
//pthread_cond_signal(&m_cond);
//pthread_mutex_unlock(&m_queue_lock);
}
*/
sleep(1000);
}
wait和notify调换,改动少许逻辑就是,countdownlatch了;
相关Linux函数:
sem_post,sem_wait,sem_init,sem_getvalue
lambda表达式:
[] (int x, int y) { return x + y; } // 隐式返回类型
[] (int& x) { ++x; } // 没有 return 语句 -> Lambda 函数的返回类型是 'void'
[] () { ++global_x; } // 没有参数,仅访问某个全局变量
[] { ++global_x; } // 与上一个相同,省略了 (操作符重载函数参数)
可以像下面这样显示指定返回类型:
[] (int x, int y) -> int { int z = x + y; return z; }
Lambda 函数可以引用在它之外声明的变量. 这些变量的集合叫做一个闭包. 闭包被定义在 Lambda 表达式声明中的方括
号 [] 内。这个机制允许这些变量被按值或按引用捕获。
[] //未定义变量.试图在Lambda内使用任何外部变量都是错误的.
[x, &y] //x 按值捕获, y 按引用捕获.
[&] //用到的任何外部变量都隐式按引用捕获
[=] //用到的任何外部变量都隐式按值捕获
[&, x] //x显式地按值捕获. 其它变量按引用捕获
[=, &z] //z按引用捕获. 其它变量按值捕获