#include <mutex>

 

多线程初级

 

 1 #include <iostream>
 2 #include <thread>
 3 #include <windows.h>
 4 #include <mutex>
 5 
 6 //两个线程并行访问一个变量
 7 
 8 int g_num = 20;//找到或者找不到的标识
 9 std::mutex g_mutex;
10 
11 void goA(int num)
12 {
13     g_mutex.lock();//你访问的变量,在你访问期间,别人访问不了
14 
15     for (int i = 0; i < 15; i++)
16     {
17         Sleep(300);
18         g_num = 10;//修改全局变量
19         std::cout << "线程" << num << "   " << g_num << std::endl;
20     }
21 
22     g_mutex.unlock();//解锁
23 }
24 
25 void goB(int num)
26 {
27     for (int i = 0; i < 15; i++)
28     {
29         Sleep(500);
30         g_num = 11;//修改全局变量
31         std::cout << "线程" << num << "   " << g_num << std::endl;
32     }
33 }
34 
35 void main()
36 {
37     std::thread t1(goA, 1);
38     std::thread t2(goB, 2);
39     t1.join();
40     t2.join();
41 
42     std::cin.get();
43 }

 

转载于:https://www.cnblogs.com/denggelin/p/5676962.html

优化这段代码 #include <iostream> #include <thread> #include <chrono> #include <mutex> #include <semaphore.h> using namespace std; // shared data resource int shared_data = 0; // semaphores for synchronization sem_t mutex, rw_mutex; // number of readers int num_readers = 0; // reader function void reader(int id) { while (true) { // acquire mutex to update the number of readers sem_wait(&mutex); num_readers++; if (num_readers == 1) { // if this is the first reader, acquire the rw_mutex sem_wait(&rw_mutex); } sem_post(&mutex); // read the shared data cout << "Reader " << id << " read shared data: " << shared_data << endl; // release mutex sem_wait(&mutex); num_readers--; if (num_readers == 0) { // if this is the last reader, release the rw_mutex sem_post(&rw_mutex); } sem_post(&mutex); // sleep for a random amount of time this_thread::sleep_for(chrono::milliseconds(rand() % 1000)); } } // writer function void writer(int id) { while (true) { // acquire the rw_mutex sem_wait(&rw_mutex); // write to the shared data shared_data++; cout << "Writer " << id << " wrote to shared data: " << shared_data << endl; // release the rw_mutex sem_post(&rw_mutex); // sleep for a random amount of time this_thread::sleep_for(chrono::milliseconds(rand() % 1000)); } } int main() { // initialize semaphores sem_init(&mutex, 0, 1); sem_init(&rw_mutex, 0, 1); // create reader threads thread readers[8]; for (int i = 0; i < 8; i++) { readers[i] = thread(reader, i); } // create writer threads thread writers[2]; for (int i = 0; i < 2; i++) { writers[i] = thread(writer, i); } // join threads for (int i = 0; i < 8; i++) { readers[i].join(); } for (int i = 0; i < 2; i++) { writers[i].join(); } // destroy semaphores sem_destroy(&mutex); sem_destroy(&rw_mutex); return 0; }
05-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值