Я не знаю откуда они такое взяли, вместе со своим университетским преподавателемOlej писал(а):Докажите, что данная задача не может быть решена с использованием двух мутексов
без использования других средств синхронизации.

Но делаем 1-й вариант, решающий такую задачу, на базе базовых POSIX pthread_t:
Код: Выделить всё
#include <pthread.h>
#include <iostream>
using namespace std;
pthread_mutex_t mux1 = PTHREAD_MUTEX_INITIALIZER,
mux2 = PTHREAD_MUTEX_INITIALIZER;
void* tfunc ( void* parm ) {
int rep = (int)parm;
for( int i = 0; i < rep; i++ ) {
pthread_mutex_lock( &mux2 );
cout << "child: строка №" << i + 1 << endl;
pthread_mutex_unlock( &mux1 );
}
return NULL;
};
int main( int argc, char *argv[] ) {
pthread_mutex_lock( &mux2 );
pthread_t tid;
const int rep = 5;
pthread_create( &tid, NULL, tfunc, (void*)rep );
for( int i = 0; i < rep; i++ ) {
pthread_mutex_lock( &mux1 );
cout << "parent: строка №" << i + 1 << endl;
pthread_mutex_unlock( &mux2 );
}
pthread_join( tid, NULL );
};
Код: Выделить всё
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mux1, mux2;
void tfunc( int rep ) {
for( int i = 0; i < rep; i++ ) {
mux2.lock();
cout << "child: строка №" << i + 1 << endl;
mux1.unlock();
}
};
int main( int argc, char *argv[] ) {
mux2.lock();
const int rep = 5;
thread thr( tfunc, rep );
for( int i = 0; i < rep; i++ ) {
mux1.lock();
cout << "parent: строка №" << i + 1 << endl;
mux2.unlock();
}
thr.join();
};
Код: Выделить всё
bash-4.2$ make
g++ -Wall -lpthread -std=c++11 2thr.cc -o 2thr
g++ -Wall -lpthread -std=c++11 2thr+.cc -o 2thr+
Код: Выделить всё
bash-4.2$ ./2thr
parent: строка №1
child: строка №1
parent: строка №2
child: строка №2
parent: строка №3
child: строка №3
parent: строка №4
child: строка №4
parent: строка №5
child: строка №5
Код: Выделить всё
bash-4.2$ ./2thr+
parent: строка №1
child: строка №1
parent: строка №2
child: строка №2
parent: строка №3
child: строка №3
parent: строка №4
child: строка №4
parent: строка №5
child: строка №5
