Synchronise two threads passing events between each other - c++

I am new to windows c++ programming. Please see the below code where I want to make the two threads synchronized. The first thread should print "Hello" then pass the control/event to the second thread. Not sure how to do it. As of now I am using Sleep(1000). But if I dont use Sleep it result into undefined behavior. Please help...
#include <windows.h>
#include <process.h>
#include <iostream>
void thread1(void*);
void thread2(void*);
int main(int argc, char **argv) {
_beginthread(&thread1,0,(void*)0);
_beginthread(&thread2,0,(void*)0);
Sleep(1000);
}
void thread1(void*)
{
std::cout<<"Hello "<<std::endl;
}
void thread2(void*)
{
std::cout<<"World"<<std::endl;
}

The problem is the question you are asking really doesn't make sense. Multiple threads are designed to run at the same time and you're trying to play a game of pass the buck from one thread to another to get sequential serialised behavoir. Its like taking a really complicated tool and ask how it solves what is normally a really easy question.
However, multithreading is a really important topic to learn so I'll try to answer what you need to the best of my ability.
Firstly, I'd recommend using the new, standard C++11 functions and libraries. For windows, you can download Visual Studio 2012 Express Edition to play about with.
With this you can use std::thread, std::mutex and a lot [but not all] of the other C++11 goodies (like std::condition_variable).
To solve your problem you really need a condition variable. This lets you signal to another thread that something is ready for them:
#include <iostream>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <thread>
static std::atomic<bool> ready;
static std::mutex lock;
static std::condition_variable cv;
// ThreadOne immediately prints Hello then 'notifies' the condition variable
void ThreadOne()
{
std::cout << "Hello ";
ready = true;
cv.notify_one();
}
// ThreadTwo waits for someone to 'notify' the condition variable then prints 'World'
// Note: The 'cv.wait' must be in a loop as spurious wake-ups for condition_variables are allowed
void ThreadTwo()
{
while(true)
{
std::unique_lock<std::mutex> stackLock(lock);
cv.wait(stackLock);
if(ready) break;
}
std::cout << "World!" << std::endl;
}
// Main just kicks off two 'std::thread's. We must wait for both those threads
// to finish before we can return from main. 'join' does this - its the std
// equivalent of calling 'WaitForSingleObject' on the thread handle. its necessary
// to call join as the standard says so - but the underlying reason is that
// when main returns global destructors will start running. If your thread is also
// running at this critical time then it will possibly access global objects which
// are destructing or have destructed which is *bad*
int main(int argc, char **argv)
{
std::thread t1([](){ThreadOne();});
std::thread t2([](){ThreadTwo();});
t1.join();
t2.join();
}

Here is the simplified version to handle your situation.
You are creating 2 threads to call 2 different function.
Ideally thread synchronization is used to serialize same code between threads but in your case it is not the need. You are trying to serialize 2 threads which are no way related to one another.
Any how you can wait for each thread to finish by not making async call.
#include <windows.h>
#include <process.h>
#include <iostream>
#include<mutex>
using namespace std;
void thread1(void*);
void thread2(void*);
int main(int argc, char **argv) {
HANDLE h1 = (HANDLE)_beginthread(&thread1,0,(void*)0);
WaitForSingleObject(h1,INFINITE);
HANDLE h2 = (HANDLE)_beginthread(&thread2,0,(void*)0);
WaitForSingleObject(h2,INFINITE);
}
void thread1(void*)
{
std::cout<<"Hello "<<std::endl;
}
void thread2(void*)
{
std::cout<<"World"<<std::endl;
}
You can group both beginthread in single function and call that function in while loop if you want to print multiple times.
void fun()
{
HANDLE h1 = (HANDLE)_beginthread(&thread1,0,(void*)0);
WaitForSingleObject(h1,INFINITE);
HANDLE h2 = (HANDLE)_beginthread(&thread2,0,(void*)0);
WaitForSingleObject(h2,INFINITE);
}

Related

List share between two threads

I would like in c++ to share a list between two threads. I would like very simple not by taking FIFO or Shared memory so i just use mutex and locks.
I tried this way and its working :
#include <string.h>
#include <mutex>
#include <iostream>
#include <thread>
#include <list>
std::list<int> myList;
std::mutex list_mutex;
void client(){
std::lock_guard<std::mutex> guard(list_mutex);
myList.push_back(4);
};
void server(){
std::lock_guard<std::mutex> guard(list_mutex);
myList.push_back(2);
};
void print(std::list<int> const &list)
{
for (auto const& i: list) {
std::cout << i << "\n";
}
};
int main(int ac, char** av)
{
std::mutex list_mutex;
std::thread t1(client);
std::thread t2(server);
t1.join();
t2.join();
print(myList);
std::cout<<"test";
return 0;
}
And it print me this
24test
This is fine it work HOWEVER i'm not sure i'm using the same lock ? My supervisor wants me to have explicit Lock/Unlock in the code. At least if i can use the same mutex?
Thank you very much to help me
Ted's comment is important, what you are working with are threads, not processes. Processes don't share memory (besides using Shared Memory, but you wanted to avoid that). Threads share their entire memory space with each other.
You also mentioned that your supervisor wants you to use unlock/lock sections. You could do this by calling:
list_mutex.lock()
... critical section ...
list_mutx.unlock()
But you already do this implicitly by constructing a lock_guard. The lock_guard locks when you create it and unlocks at the end of the current scope.
As noted by Ted, you need to remove the second declaration of list_mutex (inside main).

How to send a function to another process in C++?

I have 2 processes, one of them has to communicate with the other one.
It needs to send a function so that the other one can execute it many times.
Can it be done using shared memory, so that the sender writes the function instructions
and the receiver reads them and executes? If so, how can I get the function's binary instructions?
Is there another way to do it?
I need to do it on a Linux distribution.
If I understood what you want well, you can have to threads and a global std::promise to send a function from one thread to another one, as follows
#include <iostream>
#include <thread>
#include <future>
using namespace std::chrono_literals;
int main(){
std::promise<std::function<void(int)>> functionToBeSent;
std::thread process1{[&]{
std::this_thread::sleep_for(1s);
functionToBeSent.set_value([](int arg){std::cout << arg << "\n";});
}};
std::thread process2 {
[&] {
auto future = functionToBeSent.get_future();
while ( future.wait_for(100ms)!=std::future_status::ready);
auto functionToBeExecutedManyTimes = future.get();
int manyTimes = 100;
while(manyTimes--) {
functionToBeExecutedManyTimes(manyTimes);
}
}
};
process1.join();
process2.join();
}

"pthread_cond_wait" didn't wait main thread to sleep, why?

I did a simple experiment to test that:
Main thread create a sub thread.
Subthread wait main thread to signal the conditional variable.
The main thread sleeps 3 seconds and signals the "cond". Then I expect that sub thread will wake up from "cond_wait" and print.
Code:
#include <pthread.h>
#include <unistd.h>
#include <cassert>
#include <iostream>
using namespace std;
pthread_mutex_t mt;
pthread_cond_t cond;
pthread_t tid;
void* tf(void*arg){
pthread_mutex_lock(&mt);
pthread_cond_wait(&cond, &mt);
cout<<"After main thread sleeps 3 seconds\n";
return NULL;
}
int main(){
assert(0==pthread_mutex_init(&mt,NULL));
pthread_create(&tid,NULL,tf,NULL);
sleep(3);
pthread_cond_signal(&cond);
pthread_join(tid,NULL);//Is 2nd parameter useful?
pthread_cond_destroy(&cond);
return 0;
}
But in fact, the sub thread will print "After main thread sleeps 3 seconds" at once. Where did I get wrong?
Thanks.
Most importantly, since you attached the C++ tag to this question, use the C++ threading features, not the pthread library. You are not guaranteed to always have access to that (for example on windows), whereas std::thread is designed to be cross platform and free from some of the annoyances that come with using the pthread() library's C interface
Second, initialize your variables, C and C APIs are annoying like that. Third, you need to account for spurious wakeups, put a while loop around the condition variable wait, and attach an actual condition to it, for example
while (not_signalled) {
pthread_cond_wait(&cond, &mt);
}
What might be happening is that your thread gets woken up spuriously and then finishes since you don't have a while loop protecting against spurious wakeups
Working C++ code
#include <thread>
#include <iostream>
#include <chrono>
using std::cout;
using std::endl;
std::mutex mtx;
std::condition_variable cv;
bool has_signalled{false};
void th_function() {
// acquire the lock
auto lck = std::unique_lock<std::mutex>{mtx};
// loop to protect against spurious wakeups
while (!has_signalled) {
// sleep
cv.wait(lck);
}
cout << "Thread has been signalled" << endl;
}
int main() {
auto th = std::thread{th_function};
// sleep for 2 seconds
std::this_thread::sleep_for(std::chrono::seconds(2));
// signal and change the variable
{
std::lock_guard<std::mutex> lck{mtx};
has_signalled = true;
}
// signal
cv.notify_one();
th.join();
}
I'm not aware about the Linux threading functions but in Windows you would have to initialize the variable that corresponds to pthread_cond_t cond in Linux.
There is a manpage for a function named pthread_cond_init which seems to do exactly that.

Obtaining thread Core affinity in C++ 11 through pthreads

I'm trying to set core affinity (Thread #1 goes on first core, Thread #2 goes on second core, ...) while using std::thread in C++ 11.
I've already searched around various topics and on the internet and it seems C++ 11 API doesn't provide such low level feature.
On the other hand, pthreads come with pthread_setaffinity_np which would be useful if I could get the "pthread_t" value of my std::thread (I don't know if this is human reasonable or at least legitimate asking for it).
An example program of what I'd want to have in the end is this:
#include <thread>
#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define CORE_NO 8
using namespace std;
void run(int id) {
cout << "Hi! I'm thread " << id << endl;
// thread function goes here
}
int main() {
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
for(int i=0; i<CORE_NO; i++)
CPU_SET(i, &cpu_set);
thread t1(run, 1);
// obtaining pthread_t from t1
/*
pthread_t this_tid = foo(t1);
pthread_setaffinity_np(this_tid, sizeof(cpu_set_t), &cpu_set);
*/
t1.join();
return 0;
}
I'd really prefer not to change the whole architecture of my project (which must provide such characteristic). I've now a massive use of std::thread but I can use pthread API in addition as well, as you have seen in the example.
Is there a way for me to solve this problem?
You can get the native handle for the thread with the native_handle function.
The example in the linked reference even uses this to call pthread functions.
I do not know if it is a suitable approach in your case, but what I usually do is to call the affinity primitives from within the thread. E.g., I place a snippet of code similar to this one somewhere at the beginning of the threaded function:
const int err = pthread_setaffinity_np(pthread_self(),...);
The call to pthread_self() will return the ID of the calling thread.

Simple example of threading in C++

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
Create a function that you want the thread to execute, for example:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread> to access the std::thread class.)
The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)
The Code
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
On GCC, compile with -std=c++0x -pthread.
This should work for any operating-system, granted your compiler supports this (C++11) feature.
Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in C++0x, which was just nailed down and hasn't yet been implemented.
The problem is somewhat systemic. Technically the existing C++ memory model isn't strict enough to allow for well-defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the C++0x standard on the topic.
Threads Cannot be Implemented as a Library
That said, there are several cross-platform thread C++ libraries that work just fine in practice. The Intel thread building blocks contains a tbb::thread object that closely approximates the C++0x standard and Boost has a boost::thread library that does the same.
oneAPI Threading Building Blocks
Chapter 19. Thread (Boost documentation)
Using boost::thread, you'd get something like:
#include <boost/thread.hpp>
void task1() {
// do stuff
}
void task2() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(task1);
thread thread_2 = thread(task2);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
There is also a POSIX library for POSIX operating systems.
Check for compatibility:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout << msg << std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1, i2;
i1 = pthread_create(&thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create(&thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
Compile with -lpthread.
POSIX Threads
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
Class.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
Unless one wants a separate function in the global namespace, we can use lambda functions for creating threads.
One of the major advantage of creating a thread using lambda is that we don't need to pass local parameters as an argument list. We can use the capture list for the same and the closure property of lambda will take care of the lifecycle.
Here is sample code:
int main() {
int localVariable = 100;
thread th { [=]() {
cout << "The value of local variable => " << localVariable << endl;
}};
th.join();
return 0;
}
By far, I've found C++ lambdas to be the best way of creating threads especially for simpler thread functions.
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread &copy);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it.
More information is in the wxThread documentation.