互斥锁的版本:
#include <string>
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
std::mutex data_mutex;
int flag = 0;
void printA(int* a, int size) {
for (int i = 0; i < size; ) {
data_mutex.lock();
if (flag == 0) {
cout << a[i] << endl;
flag = 1;
++i;
}
data_mutex.unlock();
}
}
void printB(char* b, int size) {
for (int i = 0; i < size; ) {
data_mutex.lock();
if (flag == 1) {
cout << b[i] << endl;
flag = 0;
++i;
}
data_mutex.unlock();
}
}
int main()
{
int a[4] = { 1, 2, 3, 4 };
char b[4] = { 'a', 'b', 'c', 'd' };
std::thread tA(&printA, a, 4);
std::thread tB(&printB, b, 4);
tA.join();
tB.join();
return 0;
}
使用互斥锁+条件变量的版本:
#include