Inter thread communication in C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
From the main of my program I am launching to threads (A and B). Thread_A is in charge of generating blocks of a signal (it stores theses blocks in a matrix visible for both threads), whereas Thread_B is responsible for its transmission.
My goal is that each time thread_A generates a block, it has to notify thread_B for its transmission (maybe a good approach would be to send the address of the memmory blocks filled). For this purpose, I thougth to use POSIX message queues, but unfortunately I have no experience with this kind of stuff.
Can anybody provide me a simple example of inter thread communication applicable for this scenario?

Here some example with using condition variable. One thread generates signals. The other one transmits them. The signals in this example are just int's. There is also a sleep there to simulate some load. Hope this helps:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <future>
#include <thread>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <utility>
#include <chrono>
using namespace std;
bool rdy_flg;
mutex rdy_mtx;
condition_variable rdy_cond_var;
bool finished;
vector<int> my_signals;
void GenerateSignals() {
const int kNumOfTests = 10;
for (int i = 0; i < kNumOfTests; ++i) {
// 1. for each test generate some random signals - just int's in this case
int n = rand() % 11;
if (n == 0) n = 5;
vector<int> vec(n);
for (int j = 0; j < n; ++j) vec[j] = rand() % 1000;
{
// 2. now we are updating the global variable
// -> need to lock here
lock_guard<mutex> lg(rdy_mtx);
my_signals = vec;
cout << "Generating signals: ";
for (auto& v : my_signals) cout << v << " ";
cout << endl;
rdy_flg = true;
// if last test -> set finished to true for other thread
// to know to not wait for new notifications any more
if (i == kNumOfTests-1)
finished = true;
} // 3. lock guard goes out of scope -> automatic unlock
// 4. send notification to the other thread
rdy_cond_var.notify_one();
// 5. simulate some heavy work
this_thread::sleep_for(chrono::seconds(1));
}
}
void TransmitSignals() {
while (!finished) {
// need unique lock here
unique_lock<mutex> ul(rdy_mtx);
// wait for notification until rdy_flg is true - there is something to read
rdy_cond_var.wait(ul, [] { return rdy_flg; });
cout << "Transmitting signals: ";
for (auto& v : my_signals) cout << v << " ";
cout << endl;
// reset rdy_flg to false for not to process the same signals again
rdy_flg = false;
}
}
int main() {
srand(time(nullptr));
auto f1 = async(launch::async, GenerateSignals);
auto f2 = async(launch::async, TransmitSignals);
}
Here the live example: https://wandbox.org/permlink/hgoZB8POiWAYEZ5I
Here the updating example with processing the same signal repeatly :
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <condition_variable>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>
using namespace std;
mutex mtx_signals;
mutex mtx_cout;
bool finished;
vector<int> my_signals;
void GenerateSignals() {
const int kNumOfTests = 3;
for (int i = 0; i <= kNumOfTests; ++i) {
int n = rand() % 11;
if (n == 0) n = 5;
vector<int> vec(n);
for (int j = 0; j < n; ++j) vec[j] = rand() % 1000;
if (!finished) {
{
lock_guard<mutex> lg(mtx_signals);
my_signals = vec;
if (i >= kNumOfTests) finished = true;
}
if (!finished) {
lock_guard<mutex> lgcout(mtx_cout);
cout << "Generating signals: ";
for (auto& v : my_signals) cout << v << " ";
cout << endl;
}
}
this_thread::sleep_for(chrono::seconds(1));
}
}
void TransmitSignals() {
while (!finished) {
vector<int> sigs;
{
lock_guard<mutex> lg(mtx_signals);
sigs = my_signals;
}
if (sigs.size()) {
lock_guard<mutex> lgcout(mtx_cout);
cout << "Transmitting signals: ";
for (auto& v : sigs) cout << v << " ";
cout << endl;
}
this_thread::sleep_for(chrono::milliseconds(200));
}
}
int main() {
srand(time(nullptr));
auto f1 = async(launch::async, GenerateSignals);
auto f2 = async(launch::async, TransmitSignals);
}
https://wandbox.org/permlink/R7DdsdItqJX0L07k

Related

segmentation fault pushing back to vector in shared memory

I working on a program that simulates travel agents booking flights in parallel. It spins up a process for each agent and works against an array of Plane objects held in shared memory.
I'm getting a segmentation fault when I try to push a row of seats back to the plane. The method to parse the input file calls a SetSeats() method on Plane objects. Each Plane contains a vector<map<char, Seat>> (each index of the vector is a row, each key of each map is the letter of a seat on that row). When I call SetSeats() it goes fine through adding seats to the first map, i.e. the first row of seats. It throws the segfault when I try to push the map back to the seats vector.
I saw something online about pushing back custom classes to vectors needing deconstructors, so I added them to Seat.h and Plane.h.
Code for the main program:
#include <iostream>
#include <map>
#include <vector>
#incluce <string>
#include <fstream>
#include "Seat.h"
#include "Plane.h"
void ParseInputFile(ifstream &inFS, int numPlanes, int &numAgents);
int shmid;
int *timer;
int numPlanes, numAgents;
struct sembuf *ops;
Plane *sharedPlanes;
map<string, Plane*> planes;
using namespace std;
int main(int argc, char *argv[])
{
ifstream inFS;
// code to get an input file from command line arguments and get number of planes from it
// set up shared memory segment
long key = XXX; // just a long integer
int nbytes = 1024;
shmid = shmget((key_t)key, nbytes, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("Error in shared memory region setup.\n");
perror("REASON");
exit(2);
}
// initialize global variables
sharedPlanes = new Plane[numPlanes];
timer = new int;
ops = new sembuf[1];
// attached shared pointers to shared memory segment
sharedPlanes = (Plane*)shmat(shmid, (Plane*)0, 0);
timer = (int*)shmat(shmid, (int*)0, 0);
*timer = 0;
inFS.open(inputFile);
ParseInputFile(inFS, numPlanes, numAgents); // breaks in here
// the rest of main()
}
void ParseInputFile(ifstream &inFS, int numPlanes, int &numAgents)
{
string line = "";
bool foundNumberOfPlanes = false;
bool foundPlanes = false;
bool foundNumberOfAgents = false;
bool lookingForAgent = false;
bool foundAgent = false;
int planeNo = 0;
int agentNo = 0;
int opNo = 0;
map<string, Operation> ops;
vector<Request> agentRequests;
while (getline(inFS, line))
{
if (!CommonMethods::IsWhitespace(line))
{
// code to read first line
if (foundNumberOfPlanes && !foundPlanes)
{
// parse a line from the input file to get details about the plane
Plane *plane = &sharedPlanes[planeNo];
unsigned int rows = xxx; // set based on the plane details
unsigned int seatsPerRow = xxx; set based on the plane details
plane->SetSeats(rows, seatsPerRow); // this is the method where I get the seg fault
// finish defining the plane
continue;
// the rest of the method
}
}
}
}
Code for Plane.h:
#pragma once
#include <iostream>
#include <string>
#include <map>
#include <tuple>
#include <vector>
#include "Seat.h"
#include "Exceptions.h"
#include "ReservationStatus.h"
#include "CommonMethods.h"
using namespace std;
class Plane
{
private:
vector<map<char, Seat>> seats;
unsigned int numberOfRows, numberOfSeatsPerRow;
public:
Plane(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow);
Plane() {}
void SetSeats(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow);
};
void Plane::SetSeats(unsigned int numberOfRows, unsigned int numberOfSeatsPerRow)
{
//cout << "Clearing old seats" << endl;
if (!seats.empty())
{
//cout << "Seats not empty" << endl;
for (int i = 0; i < (int)seats.size(); i++)
{
//cout << "checking row " << i << endl;
if (!seats.at(i).empty())
{
//cout << "Row " << i << " not empty" << endl;
seats.at(i).clear();
}
}
}
cout << "Rows: " << numberOfRows << ", Seats: " << numberOfSeatsPerRow << endl;
this->numberOfRows = numberOfRows;
this->numberOfSeatsPerRow = numberOfSeatsPerRow;
for (unsigned int i = 0; i < this->numberOfRows; i++)
{
map<char, Seat> row;
for (unsigned int j = 0; j < this->numberOfSeatsPerRow; j++)
{
Seat seat;
seat.RowNumber = i + 1;
seat.SeatLetter = j + 'A';
//cout << "Inserting seat " << seat.RowNumber << seat.SeatLetter << endl;
row.insert(pair<char, Seat>(seat.SeatLetter, seat));
}
if (!row.empty())
{
cout << "inserting row " << (i + 1) << endl;
seats.push_back(row);
}
}
}
void Plane::ProcessWaitAny(int t)
{
while (!WaitingList.empty())
{
bool booked = false;
string pass = WaitingList.front();
WaitingList.pop();
for (unsigned int j = 0; j < numberOfRows; j++)
{
if (booked)
break;
for (unsigned int k = 0; k < numberOfSeatsPerRow; k++)
{
Seat *s = &seats.at(j)[k + 'A'];
if (!s->IsBooked)
{
Reserve(s, pass);
booked = true;
string seatNo = to_string(j);
seatNo += (k + 'A');
cout << "Passenger " << pass << " booked into seat " << seatNo << " at time " << t << endl;
break;
}
}
}
if (!booked)
return;
}
}
Code for Seat.h
#pragma once
#include <iostream>
#include <string>
#include <queue>
using namespace std;
struct Seat
{
string Passenger = "";
bool IsBooked = false;
unsigned int RowNumber;
char SeatLetter;
queue<string> WaitingList;
};
I have made a minimum working example of your problem:
#include <vector>
#include <sys/shm.h>
#include <iostream>
class Bar {
public:
Bar() {};
std::vector<int> vec;
};
int main() {
int shmid;
Bar* a = new Bar();
a->vec.push_back(1);
// set up shared memory segment
long key = 0x123455; // just a long integer
int nbytes = 1024;
shmid = shmget((key_t)key, nbytes, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("Error in shared memory region setup.\n");
perror("REASON");
exit(2);
}
a = (Bar*)shmat(shmid, (Bar*)0, 0);
a->vec.push_back(2);
}
The problem is your wrong usage of shmat. The pointer sharedPlane just points to some unitialized shared memory. You have to make sure that the address provided by key is 'right'. To do this, do the following:
Your other process, call Plane * other_process_sharedPlane = new Plane();. Remove the line sharedPlanes = new Plane[numPlanes]; from your main programm.
In your main process, set key to the value of other_process_sharedPlane
Then you can call shmget and shmadd

Why program works correctly while join only 1 thread but there are 5

This is my code and I accidentally made a mistake buy not making the for loop longer but the code works as intended.
What happens after the program is completed? Does it have any fail cases or does the computer auto kill all thread and if there would be any additional code it Threads again would there be problems( for example if i would initiate 2 thread then there would be 6 thread working and the new thread ids would be 5 and 7?)
#include <iomanip>
#include <thread>
#include <iostream>
#include <mutex>
#include <sstream>
#include <vector>
#include <conio.h>
using namespace std;
bool endProgram = false;
struct Monitorius {
public:
int IOCounter = 0;
int readCounterC = 0;
int readCounterD = 0;
condition_variable cv;
mutex mtx;
int c = 10;
int d = 100;
Monitorius() {
c = 10;
d = 100;
IOCounter = 0;
readCounterC = 0;
readCounterD = 0;
}
void changeC(int i) {
while (!endProgram) {
unique_lock<mutex> lck(mtx);
cv.wait(lck, [&] {return readCounterC > 1; });
if (!endProgram) {
c += i;
readCounterC = 0;
cv.notify_all();
}
}
}
void changeD(int i) {
while (!endProgram) {
unique_lock<mutex> lck(mtx);
cv.wait(lck, [&] {return readCounterD > 1; });
if (!endProgram) {
d -= i;
readCounterD = 0;
cv.notify_all();
}
}
}
void readCD(int i) {
int oldC = -1;
int oldD = -1;
while (!endProgram) {
unique_lock<mutex> lck(mtx);
cv.wait(lck, [&] {return oldC != c && oldD != d; });
if (!endProgram) {
stringstream str;
str << i << ": c:" << c << " d: " << d << endl;
cout << str.str();
readCounterC++;
readCounterD++;
IOCounter++;
if (IOCounter >= 15)
endProgram = true;
cv.notify_all();
oldC = c;
oldD = d;
}
}
}
};
int main()
{
Monitorius M;
vector<thread> myThreads;
myThreads.reserve(5);
myThreads.emplace_back([&] { M.changeC(1); });
myThreads.emplace_back([&] { M.changeD(2); });
myThreads.emplace_back([&] { M.readCD(3); });
myThreads.emplace_back([&] { M.readCD(4); });
myThreads.emplace_back([&] { M.readCD(5); });
for (size_t i = 0; i < 1; i++)
myThreads[i].join();
_getch();
}
When your main function exits, all the threads in the vector will be destructed.
If they are not joined at that time std::terminate should be called by the std::thread destructor.
By detaching threads the thread-objects can be destructed and the thread still continues to run. But then on the common modern operating systems when the process ends (which happens after main have returned or exit is called) the threads will be killed anyway. To let threads continue running even after the "main" thread ends, you have to call a system-dependent function to exit the "main" thread.
I do not know if it's possible to do this on Windows though, as the ExitThread function should not be used by C++ code as it exits the thread without destructing objects.
The solution to both problems is of course to properly join all threads.

Synchronize two functions

I am currently trying to sync two different funtions to fill a vector with numbers. One function fills the vector with even numbers, the other one with odd numbers. The numbers should be inserted in the correct order in the vector (that the result is: numbers [i] = i)
void incOdd(std::vector<uint8_t> *numbers, TestMutex *inEven, TestMutex *inOdd){
for(uint8_t i = 1; i < 100;i++){
if((i + 1) % 2 == 0){
continue;
}
inOdd->lock();
(*numbers).push_back(i);
inOdd->unlock();
}
}
void incEven(std::vector<uint8_t> *numbers, TestMutex *inEven, TestMutex *inOdd){
for(uint8_t i = 0; i < 100;i++){
if(i % 2 != 0){
continue;
}
inEven->lock();
(*numbers).push_back(i);
inEven->unlock();
}
}
Just a Note: Test mutex is just a class that is a child of the mutex where only the lock and unlock function are defined. ( the lock function has a counter for the tests later)
Since it is a practice task, the parameters must not be changed and work only in parentheses. I Already tried to use condition_variables to let them wait for each other but it doesn't worked.
I have no other approaches and hope you have a solution for me
Update:
TEST_CASE("synchronize [thread]") {
TestMutex inEven;
TestMutex inOdd;
inEven.lock();
std::vector<uint8_t> numbers;
std::thread even(incEven,&numbers,&inEven,&inOdd);
std::thread odd(incOdd,&numbers,&inEven,&inOdd);
odd.join();
even.join();
for(size_t i=0; i < numbers.size(); i++) {
REQUIRE(numbers[i] == (i+1));
}
REQUIRE(numbers.size() == 100);
REQUIRE(inEven.c==51);
REQUIRE(inOdd.c==50);
}
So this is the Test Case i have to solve for this question i am not allowd to change this.
See my code which is self explanatory:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
bool odd = false;
typedef mutex TestMutex;
void incOdd(std::vector<uint8_t> *numbers,TestMutex *inEven,TestMutex *inOdd) {
for (uint8_t i = 0; i < 100; i++) {
if (i % 2 == 0) {
unique_lock<mutex> lock(*inEven);
cv.wait(lock, []() { return odd == false; });
numbers->push_back(i);
odd = true;
cv.notify_one();
}
}
}
void incEven(std::vector<uint8_t> *numbers, TestMutex *inEven, TestMutex *inOdd) {
for (uint8_t i = 0; i < 100; i++) {
if (i % 2 != 0) {
unique_lock<mutex> lock(*inEven);
cv.wait(lock, []() { return odd == true; });
numbers->push_back(i);
odd = false;
cv.notify_one();
}
}
}
int main()
{
vector<uint8_t> vec;
TestMutex mu;
TestMutex rmu; // redundant
thread thread1([&]() { incEven(&vec,&mu,&rmu); });
thread thread2([&]() { incOdd(&vec,&mu,&rmu); });
thread1.join();
thread2.join();
for (auto e : vec)
cout << int(e) << endl;
return 0;
}

When I use thread and mutex, C++ occur Memory leak

I want store integer to write_odd_queue, then popping integer from another thread.
data_prepation_thread function will store integer to write_odd_queue.
handle_odd function will pop integer from write_odd_queue.
When I write Sleep(10), memory will not increase.
When I comment this code, memory will increase.
Please help me solve this problem.
#include <iostream>
#include <vector>
#include <thread>
#include <random>
#include <windows.h>
#include <time.h>
#include <mutex>
#include <queue>
#include <condition_variable>
using namespace std;
queue<int> write_odd_queue;
mutex write_odd_mutux;
void handle_odd()
{
while (true)
{
int i;
{
lock_guard<mutex> lk(write_odd_mutux);
if (!write_odd_queue.empty())
{
i = write_odd_queue.front();
write_odd_queue.pop();
cout << "test size " << write_odd_queue.empty() << " ";
}
else
{
continue;
}
}
cout << "odd " << i << endl;
Sleep(500);
}
}
void data_prepation_thread()
{
int i = 0;
while (true)
{
i++;
unique_lock<mutex> lk(write_odd_mutux);
write_odd_queue.push(i);
lk.unlock();
// comment Sleep(10), memory will not increase.
//Sleep(10);
}
}
int main()
{
vector<thread> vec;
thread t1(handle_odd);
vec.push_back(move(t1));
data_prepation_thread();
auto it = vec.begin();
for (; it != vec.end(); ++it)
{
it->join();
}
return 0;
}
You are removing things from the queue with a delay of 500 milliseconds, and pushing them on to the queue with no delay - this means the queue will grow, as the frequency of your pops is not matching that of your pushes. Adding a delay to the pushes will reduce the growth, so that it may not be obvious for short runs of the program.
This is solution to avoid Sleep() in both functions using condition variables:
queue<int> write_odd_queue;
mutex write_odd_mutux;
condition_variable data_ready;
condition_variable queue_ready;
bool stopped = false;
const size_t max_size = 1024;
const size_t min_size = 512;
void handle_odd()
{
unique_lock<mutex> lk(write_odd_mutux);
while (!stopped)
{
if( write_odd_queue.empty() ) {
data_ready.wait( lk );
continue;
}
int i = write_odd_queue.front();
write_odd_queue.pop();
if( write_odd_queue.size() == min_size )
queue_ready.notify_one();
cout << "test size " << write_odd_queue.empty() << " ";
lk.unlock();
cout << "odd " << i << endl;
lk.lock();
}
}
void data_prepation_thread()
{
int i = 0;
while (!stopped)
{
unique_lock<mutex> lk(write_odd_mutux);
if( write_odd_queue.size() >= max_size ) {
queue_ready.wait( lk );
continue;
}
write_odd_queue.push(++i);
if( write_odd_queue.size() == 1 )
data_ready.notify_all();
}
}
void stop()
{
unique_lock<mutex> lk(write_odd_mutux);
stopped = true;
data_ready.notify_all();
queue_ready.notify_all();
}
This will prevent queue to grow bigger than max_size and reenable pushing when size drops to min_size. Also there is no unnecessary delay in processing would be involved, as you would have with Sleep(500).

printing odd and even number printing alternately using threads in C++

Odd even number printing using thread I came across this question and wanted to discuss solution in C++ . What I can think of using 2 binary semaphores odd and even semaphore. even semaphore initialized to 1 and odd initialized to 0.
**T1 thread function**
funOdd()
{
wait(even)
print odd;
signal(odd)
}
**T2 thread function**
funEven()
{
wait(odd)
print even
signal(even)
}
In addition to this if my functions are generating only number and there is a third thread T3 which is going to print those numbers then what should be ideal design ? I used an array where odd number will be placed at odd place and even number will be place at even position. T3 will read from this array this will avoid any thread saftey over this array and if T3 does not find any index then it will wait till that index gets populated. Another solution can be to use a queue which will have a mutex which can be used by T1 and T2 while insertion.
Please comment on this solution and how can i make it more efficient.
Edit to make problem much clear: Overall problem is that I have two producers (T1,T2) and a single consumer (T3), and my producers are interdependent.
Using condition_variable
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mu;
std::condition_variable cond;
int count = 1;
void PrintOdd()
{
for(; count < 100;)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker,[](){ return (count%2 == 1); });
std::cout << "From Odd: " << count << std::endl;
count++;
locker.unlock();
cond.notify_all();
}
}
void PrintEven()
{
for(; count < 100;)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker,[](){ return (count%2 == 0); });
std::cout << "From Even: " << count << std::endl;
count++;
locker.unlock();
cond.notify_all();
}
}
int main()
{
std::thread t1(PrintOdd);
std::thread t2(PrintEven);
t1.join();
t2.join();
return 0;
}
Solution using condition variable.
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
mutex oddevenMu;
condition_variable condVar;
int number = 1;
void printEvenOdd(bool isEven, int maxnubmer)
{
unique_lock<mutex> ul(oddevenMu);
while (number < maxnubmer)
{
condVar.wait(ul, [&]() {return number % 2 == isEven;});
cout << number++ << " ";
condVar.notify_all();
}
}
int main(string args[])
{
thread oddThread(printEvenOdd, false, 100);
thread evenThread(printEvenOdd, true, 100);
oddThread.join();
evenThread.join();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
sem_t sem;
sem_t sem2;
using namespace std ;
int count = 1;
void increment(int x)
{
cout << "called by thread : " << x << "count is : " << count ++ << "\n";
}
void *printAltmessage1(void *thread_value)
{
for(int m=0; m < (*(int *)thread_value); m++)
{
if (sem_wait(&sem) == 0)
{
cout << " Thread printAltmessage1 is executed" <<"\n";
increment(1);
sem_post(&sem2);
}
}
}
void *printAltmessage2(void *thread_value)
{
for(int m=0; m < (*(int *)thread_value); m++)
{
if (sem_wait(&sem2) == 0)
{
cout << " Thread printAltmessage2 is executed" <<"\n";
increment(2);
sem_post(&sem);
}
}
}
int main()
{
sem_init(&sem,0, 1);
sem_init(&sem2,0, 0);
pthread_t threads[2];
int x =8;
for(int i=0;i<2;i++)
{
if(i==0)
int rc =pthread_create(&threads[i],NULL,printAltmessage1,(void*)&x);
else
int rc =pthread_create(&threads[i],NULL,printAltmessage2,(void*)&x);
}
pthread_exit(NULL);
return 0;
}
This is the easiest solution you can refer:
#include<iostream>
#include<mutex>
#include<pthread.h>
#include<cstdlib>
int count=0;
using namespace std;
mutex m;
void* printEven(void *a)
{
while(1)
{
m.lock();
if(count%2==0)
{
cout<<" I am Even"<<count<<endl;
count++;
}
if(count==100)
break;
m.unlock();
}
}
void* printOdd(void *b)
{
while(1)
{
m.lock();
if(count%2!=0)
{
cout<<"I am odd"<<count<<endl;
count++;
}
if(count>100)
break;
m.unlock();
}
}
int main()
{
int *ptr = new int();
pthread_t thread1, thread2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&thread1,&attr,&printEven,NULL);
pthread_create(&thread2,&attr,&printOdd, NULL);
pthread_join(thread1,&ptr);
pthread_join(thread2,&ptr);
delete ptr;
}
This is simple solution using single function.
#include <iostream>
#include <thread>
#include <condition_variable>
using namespace std;
mutex mu;
condition_variable cond;
int count = 1;
void PrintOddAndEven(bool even, int n){
while(count < n){
unique_lock<mutex> lk(mu);
cond.wait(lk, [&](){return count%2 == even;});
cout << count++ << " ";
lk.unlock();
cond.notify_all();
}
}
int main() {
int n = 10;
thread t1(PrintOddAndEven, true, n);
thread t2(PrintOddAndEven, false, n);
t1.join();
t2.join();
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
std::mutex m;
int count = 0;
void printEven()
{
cout << "Entered Even\n" << endl;
while(count <= 10)
{
m.lock();
if(count%2 == 0)
cout << count++ << " ";
m.unlock();
}
}
void printOdd()
{
cout << "Entered Odd" << endl;
while(count < 10)
{
m.lock();
if(count%2 == 1)
cout << count++ << " ";
m.unlock();
}
}
int main()
{
std::thread t1(printOdd);
std::thread t2(printEven);
t1.join();
t2.join();
return 0;
}
#include "threadFunc.hpp"
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex t1;
condition_variable cond;
int number = 11;
int count = 0;
void printEven()
{
while(1)
{
unique_lock<mutex> ul(t1);
if(count< number)
{
if(count % 2 != 0)
{
cond.wait(ul);
}
cout<<count<<" : printed by thread"<<this_thread::get_id()<<endl;
count++;
}
if(count > number)
break;
ul.unlock();
cond.notify_all();
}
}
void printOdd()
{
while(1)
{
unique_lock<mutex> ul(t1);
if(count< number)
{
if(count % 2 == 0)
{
cond.wait(ul);
}
cout<<count<<" : printed by thread"<<this_thread::get_id()<<endl;
count++;
}
if(count > number)
break;
ul.unlock();
cond.notify_all();
}
}
I fail to understand why you want to use three separate threads for a serial behavior. But I will answer anyway:)
One solution would be to use a modified producer/consumer pattern with a prioritized queue between producers and consumers. The sort operation on the queue would depend on the integer value of the posted message. The consumer would peek an element in the queue and check if it is the next expected element. If not, it would sleep/wait.
A bit of code:
class Elt implements Comparable<Elt> {
int value;
Elt(value) { this.value=value; }
int compare(Elt elt);
}
class EltQueue extends PriorityBlockingQueue<Elt> { // you shouldn't inherit colelctions, has-a is better, but to make it short
static EltQueue getInstance(); // singleton pattern
}
class Consumer{
Elt prevElt = new Elt(-1);
void work()
{
Elt elt = EltQueue.getInstance().peek();
if (elt.getValue() == prevElt.getValue()+1)) {
EltQueue.getInstance().poll();
//do work on Elt
}
}
}
class Producer {
int n=0; // or 1!
void work() {
EltQueue.getInstance().put(new Elt(n+=2));
}
}
As a first thing, the two functions should a least contain a loop, (unless you just want a single number)
A more standard solution (which remaps your idea) is to have a global structure containing a a mutex, and two condition variables (odd and even) plus a return value, and another condition for the printing. than use a uique_lock to handle the synchronization.
IN PSEUDOCODE:
struct global_t
{
mutex mtx;
int value = {0};
condition_variable be_odd, be_even, print_it;
bool bye = {false};
global_t() { be_odd.notify(); }
} global;
void odd_generator()
{
int my_odd = 1;
for(;;)
{
unique_lock lock(global.mtx);
if(global.bye) return;
global.be_odd.wait(lock);
global_value = my_odd; my_odd+=2;
global.print_it.notify();
if(my_odd > 100) bye=true;
} //let RAII to manage wait states and unlocking
};
void even_generator()
{ /* same as odd, with inverted roles */ }
void printer()
{
for(;;)
{
unique_lock lock(global.mtx);
if(bye) return;
global.ptint_it.wait(lock);
std::cout << global.value << std::endl;
((global.value & 1)? global.be_even: global.be_odd).notify();
}
}
int main()
{
thread oddt(odd_generator), event(even_generator), printt(printer);
oddt.join(), event.join(), printer.join();
}
Note that, apart didactic purpose, this solution adds no value respect to a simple loop printing the value of a counter, since there will never be real concurrency.
Note also (to avoid globals) that you can wrap everything into a class (making the actual main a class method) and instantate that class on the stack inside the new main.
Solution is based on C++11 critical code section aka mutex.
Here's the working code, followed by an explanation.
Tested and working on VS2013:
using namespace std;
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
std::mutex mtx;
void oddAndEven(int n, int end);
int main()
{
std::thread odd(oddAndEven, 1, 10);
std::thread Even(oddAndEven, 2, 10);
odd.join();
Even.join();
return 0;
}
void oddAndEven(int n, int end){
int x = n;
for (; x < end;){
mtx.lock();
std::cout << n << " - " << x << endl;
x += 2;
mtx.unlock();
std::this_thread::yield();
continue;
}
}
i.e:
Thread odd goes to method oddAndEven with starting number 1 thus he is the odd. He is the first to acquire the lock which is the mtx.lock().
Meanwhile, thread Even tries to acquire the lock too but thread odd acquired it first so thread Even waits.
Back to thread odd (which has the lock), he prints the number 1 and releases the lock with mtx.unlock(). At this moment, we want thread Even to acquire lock and to print 2 so we notify thread Even by writing std::this_thread::yield(). Then thread Even does the same.
etc etc etc.
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mu;
unsigned int change = 0;
void printConsecutiveNumbers(int start, int end,unsigned int consecutive)
{
int x = start;
while (x < end)
{
//each thread has check there time is coming or not
if (change % consecutive == start)
{
std::unique_lock<std::mutex> locker(mu);
std::cout << "Thread " << start << " -> " << x << std::endl;
x += consecutive;
change++;
//to counter overflow
change %= consecutive;
}
}
}
int main()
{
//change num = 2 for printing odd and even
const int num = 7;
const int endValue = 1000;
std::thread threads[num];
//Create each consecutive threads
for (int i = 0; i < num; i++)
{
threads[i] = std::thread(printConsecutiveNumbers, i, endValue, num);
}
//Joins all thread to the main thread
for (int i = 0; i < num; i++)
{
threads[i].join();
}
return 0;
}
This code will work . I have tested it on visual studio 2017
#include "stdafx.h"
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
using namespace std;
mutex m;
condition_variable cv;
int num = 1;
void oddThread() {​​​​​​​
for (; num < 10;) {​​​​​​​
unique_lock<mutex> lg(m);
cv.wait(lg, [] {​​​​​​​return (num % 2 ==1); }​​​​​​​);
cout << "From odd Thread " << num << endl;
num++;
lg.unlock();
cv.notify_one();
}​​​​​​​
}​​​​​​​
void evenThread() {​​​​​​​
for (; num < 100;) {​​​​​​​
unique_lock<mutex> lg(m);
cv.wait(lg, [] {​​​​​​​return (num % 2 == 0); }​​​​​​​);
cout << "From even Thread " << num << endl;
num++;
lg.unlock();
cv.notify_one();
}​​​​​​​
}​​​​​​​
int main() {​​​​​​​
thread t1{​​​​​​​ oddThread}​​​​​​​; //odd function thread
thread t2{​​​​​​​ evenThread}​​​​​​​;
t1.join();
t2.join();
cin.get();
return 0;
}​​​​​​​
output
from oddThread: 1
from evenThread: 2
from oddThread: 3
from evenThread: 4
from oddThread: 5
from evenThread: 6
from oddThread: 7
from evenThread: 8
from oddThread: 9
from evenThread: 10
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex m;
std::condition_variable cv;
int counter =1;
void printEven()
{
std::unique_lock<std::mutex> lk(m);
while(1)
{
if(counter > 10)
break;
if(counter %2 != 0)
{
cv.wait (lk);
}
else
{
cout << "counter : " << counter << endl;
counter++;
//lk.unlock();
cv.notify_one();
}
}
}
void printOdd()
{
std::unique_lock<std::mutex> lk(m);
while(1)
{
if(counter > 9)
break;
if(counter %2 == 0)
{
cv.wait (lk);
}
else
{
cout << "counter : " << counter << endl;
counter++;
//lk.unlock();
cv.notify_one();
}
}
}
int main()
{
std::thread t1(printEven);
std::thread t2(printOdd);
t1.join();
t2.join();
cout << "Main Ends" << endl;
}
i have used anonymous func (lambda) to do this and clubbed cond variable and mutex.
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
using namespace std;
int main() {
int count = 1;
mutex mtx;
condition_variable condition;
const int ITERATIONS = 20; // iterations
//prints odd numbers
thread t1([&]() {
while (count < ITERATIONS)
{
unique_lock <mutex> lock(mtx);
condition.wait(lock, [&]() {
return count % 2 != 0;
});
cout << "thread1 prints: " << count << endl;
count++;
lock.unlock();
condition.notify_all();
}
});
thread t2([&]
{
while (count < ITERATIONS)
{
unique_lock <mutex> lock(mtx);
condition.wait(lock, [&]() {
return count % 2 == 0;
});
cout << "thread2 prints: " << count << endl;
count++;
lock.unlock();
condition.notify_all();
}
});
t1.join();
t2.join();
}
#include <bits/stdc++.h>
#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex m;
condition_variable cv;
unique_lock<mutex> lck(m);
void *printeven(void *arg)
{
int *n = (int *)arg;
while (*n <= 100)
{
cv.wait(lck);
*n = *((int *)arg);
cout << this_thread::get_id() << " : " << *n << endl;
*n = *n + 1;
cv.notify_one();
}
exit(0);
}
void *printodd(void *arg)
{
int *n = (int *)arg;
while (*n <= 100)
{
*n = *((int *)arg);
cout << this_thread::get_id() << " : " << *n << endl;
*n = *n + 1;
cv.notify_one();
cv.wait(lck);
}
exit(0);
}
int main()
{
int num = 1;
pthread_t p1 = 1;
pthread_t p2 = 2;
pthread_create(&p1, NULL, printodd, &num);
pthread_create(&p2, NULL, printeven, &num);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
return 0;
}
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable even_to_odd;
std::condition_variable odd_to_even;
unsigned int count = 1;
constexpr int MAX_COUNT = 20;
void even(int n) {
for (int i = n; i <= MAX_COUNT; i++) {
std::unique_lock<std::mutex> lock(mtx);
if (i %2 == 0) {
odd_to_even.wait(lock);
std::cout << "Even: " << i << std::endl;
even_to_odd.notify_one();
}
}
}
void odd(int n) {
for (int i = n; i <= MAX_COUNT; i++) {
std::unique_lock<std::mutex> lock(mtx);
if (i == 1) {
std::cout << "Odd : " << i << std::endl;
odd_to_even.notify_one();
}
else if (i % 2 != 0) {
even_to_odd.wait(lock);
std::cout << "Odd : " << i << std::endl;
odd_to_even.notify_one();
}
}
}
int main() {
std::thread thread1(even,count);
std::thread thread2(odd,count);
thread1.join();
thread2.join();
return 0;
}
Please see below working code (VS2005)
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <process.h>
#define MAX 100
int shared_value = 0;
CRITICAL_SECTION cs;
unsigned _stdcall even_thread_cs(void *p)
{
for( int i = 0 ; i < MAX ; i++ )
{
EnterCriticalSection(&cs);
if( shared_value % 2 == 0 )
{
printf("\n%d", i);
}
LeaveCriticalSection(&cs);
}
return 0;
}
unsigned _stdcall odd_thread_cs(void *p)
{
for( int i = 0 ; i < MAX ; i++ )
{
EnterCriticalSection(&cs);
if( shared_value % 2 != 0 )
{
printf("\n%d", i);
}
LeaveCriticalSection(&cs);
}
return 0;
}
int main(int argc, char* argv[])
{
InitializeCriticalSection(&cs);
_beginthreadex(NULL, NULL, even_thread_cs, 0,0, 0);
_beginthreadex(NULL, NULL, odd_thread_cs, 0,0, 0);
getchar();
return 0;
}
Here, using shared variable shared_value, we are synchronizing the even_thread_cs and odd_thread_cs.
Note that sleep is not used.