c++ multithread [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
c++ multithread
I use c++ to implement a thread class. The code is in the following.
I initialize two objects, wish it will start two threads (I use pthread_self() to look the thread Id).
But the result shows that there is only one thread beside the main thread.
I am a bit confused...
class Thread {
public:
int mask;
pthread_t thread;
Thread( int );
void start();
static void * EntryPoint (void *);
void Run();
};
Thread::Thread( int a) {
mask =a;
}
void Thread::Run() {
cout<<"thread begin to run" <<endl;
cout <<" Thread Id is: "<< pthread_self() << endl; // the same thread Id.
}
void * Thread::EntryPoint(void * pthis) {
cout << "entry" <<endl;
Thread *pt = (Thread *) pthis;
pt->Run();
}
void Thread::start() {
pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
pthread_join(thread, NULL);
}
int main() {
int input_array[8]={3,1,2,5,6,8,7,4};
Thread t1(1);
Thread t2(2);
t1.start();
t2.start()
}

You are seeing this behavior because you join with each of your threads immediately after you spawn them.
When you join with a thread, you block until the thread terminates.

You are spawning two threads, but the first thread is joined (and destroyed) before the second thread is spawned, so you have effectively only one thread running at a time. The way to fix this is:
Create a separate join function that invokes join().
Do not call join directly from your start() function.
In your join() function, be sure to mark the thread as having been joined/destroyed.
In your destructor, if your thread has not been joined, then you should detach it.
I should also point out that boost::thread provides cross-platform multithreading for C++.

Related

If I create two std::thread, how can I identify which thread ends first

I want to create two std::thread processes. Then I want to figure out which thread ended first and end the other thread if it is still running (probably by calling its destructor?). I would like to only use the std libraries. I'm guessing I need to do something with std::atomic and/or std::future, or implement a callback?
int process1( void );
int process2( void );
std::thread first (process1() );
std::thread second (process2() );
//check which thread is done first and call join() on that thread to end it nicely?
//kill the other thread if its not done or call join() if it is done?
You can't just end a thread from outside the thread itself. You have to signal the thread in some way that it needs to stop. You can do this with a std::atomic_boolfor example.
Something like this:
// thread-safe output
#define con_sync_out(m) do{std::ostringstream o; o<<m<<'\n'; std::cout<<o.str();}while(0)
#define con_sync_err(m) do{std::ostringstream o; o<<m<<'\n'; std::cerr<<o.str();}while(0)
// random numbers
template<typename Integer>
Integer random(Integer lo, Integer hi)
{
thread_local std::mt19937 mt{std::random_device{}()};
return std::uniform_int_distribution<Integer>(lo, hi)(mt);
}
// stuff to do
void do_work(char const* id, int a, int b, std::atomic_bool& done)
{
// check if done == true (signal to stop)
while(!done && a < b)
{
++a;
con_sync_out(id << ": " << a << "/" << b);
std::this_thread::sleep_for(std::chrono::milliseconds(random<int>(500, 1000)));
}
done = true;
}
int main()
{
std::atomic_bool done = false; // signal flag
std::thread t1(do_work, "A", random<int>(0, 10), random<int>(10, 20), std::ref(done));
std::thread t2(do_work, "B", random<int>(0, 10), random<int>(10, 20), std::ref(done));
t1.join();
t2.join();
}
There's no standard/easy way to kill a thread in C++. They're not like processes.
Either detach() them both and wait in your main thread for a std::conditional_variable notification from the fastest thread if you don't mind letting the slower one finish in the background.
Or join() them both and periodically check for the std::conditional_variable in each thread to notify that the other one has finished, and then abort by returning earlier.
If neither join() nor detach() have been called before a non-empty std::thread is destroyed, then the program simply terminates.

main thread waits for std::async to complete [duplicate]

This question already has answers here:
Can I use std::async without waiting for the future limitation?
(5 answers)
Closed 5 years ago.
I am using std::async to create a thread, I want this new thread should execute separately and main thread should not wait for it. But here when I call std::async, a new thread is created but main thread is waiting for completion of fun(). I want main thread to execute parallely without waiting for fun() to complete. How should I do that?
#include <iostream>
#include <windows.h>
#include <future>
using namespace std;
void printid()
{
cout << "Thread id is:" << this_thread::get_id() << endl;
}
void fun(void *obj)
{
cout<<"Entry"<<endl;
printid();
Sleep(10000);
cout<<"Exit"<<endl;
}
int main()
{
cout<<"Hello"<<endl;
printid();
std::async(std::launch::async, fun, nullptr);
cout << "After call" << endl;
}
I am getting output:
Hello
Thread id is:22832
Entry
Thread id is:13156
Exit
After call
A std::future object returned by std::async and launched with std::launch::async policy, blocks on destruction until the task that was launched has completed.
Since you do not store the returned std::future in a variable, it is destroyed at the end of the statement with std::async and as such, main cannot continue until the task is done.
If you store the std::future object, its lifetime will be extended to the end of main and you get the behavior you want.
int main()
{
...
auto fut = std::async(std::launch::async, fun, nullptr);
...
}
std::async(std::launch::async, fun, nullptr);
Doesn't do anything with the returned std::future, leaving it to be destroyed. That's a problem because std::future's destructor may block and wait for the thread to finish.
The solution is to hold on to the std::future for a while and let it be destroyed after you're done with everything else.
auto locallyScopedVariable = std::async(std::launch::async, fun, nullptr);
locallyScopedVariable will go out of scope at the end of main and then block until it completes.
Note that this still might not do quite what you want. The main thread could immediately yield the processor to the new thread and allow the new thread to run to completion before control is returned. The code can be corrected and still result in the output of the incorrect version.
(1) In multi-threading program testing, protect shared resource (cout in this case) from being invoked from different threads at same time using a mutex.
(2) Check if future is ready in the main, you can do a timeout also.
void print_id()
{
lock_guard<mutex> locker(mutex_);
cout << "Thread id is:" << this_thread::get_id() << endl;
}
void print( string str)
{
lock_guard<mutex> locker(mutex_);
cout << str << '\n';
}
bool fun(void *obj)
{
print("Entry");
printid();
Sleep(10000);
print("Exit");
return true;
}
int main()
{
print("Hello");
printid();
std::future<bool> fut = std::async(std::launch::async, fun,nullptr);
while(!fut->_Is_ready() )
{
}
cout << "After call" << endl;
}

C++11 std::threads and waiting for threads to finish

I have a vector of Timer Objects. Each Timer Object launches an std::thread that simulates a growing period. I am using a Command pattern.
What is happening is each Timer is getting executed one after another but what I really want is for one to be executed....then once finished, the next one...once finished the next...while not interfering with the main execution of the program
class Timer
{
public:
bool _bTimerStarted;
bool _bTimerCompleted;
int _timerDuration;
virtual ~Timer() { }
virtual void execute()=0;
virtual void runTimer()=0;
inline void setDuration(int _s) { _timerDuration = _s; };
inline int getDuration() { return _timerDuration; };
inline bool isTimerComplete() { return _bTimerCompleted; };
};
class GrowingTimer : public Timer
{
public:
void execute()
{
//std::cout << "Timer execute..." << std::endl;
_bTimerStarted = false;
_bTimerCompleted = false;
//std::thread t1(&GrowingTimer::runTimer, this); //Launch a thread
//t1.detach();
runTimer();
}
void runTimer()
{
//std::cout << "Timer runTimer..." << std::endl;
_bTimerStarted = true;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
_bTimerCompleted = true;
std::cout << "Growing Timer Finished..." << std::endl;
}
};
class Timers
{
std::vector<Timer*> _timers;
struct ExecuteTimer
{
void operator()(Timer* _timer) { _timer->execute(); }
};
public:
void add_timer(Timer& _timer) { _timers.push_back(&_timer); }
void execute()
{
//std::for_each(_timers.begin(), _timers.end(), ExecuteTimer());
for (int i=0; i < _timers.size(); i++)
{
Timer* _t = _timers.at(i);
_t->execute();
//while ( ! _t->isTimerComplete())
//{
//}
}
}
};
Executing the above like:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
start_timers();
}
void start_timers()
{
_timer.execute();
}
In Timers::execute I am trying a few different ways to execute the first and not execute the
next until I somehow signal it is done.
UPDATE:
I am now doing this to execute everything:
Timers _timer;
GrowingTimer _g, g1;
_g.setDuration(BROCCOLI::growTimeSeconds);
_g1.setDuration(BROCCOLI::growTimeSeconds);
_timer.add_timer(_g);
_timer.add_timer(_g1);
//start_timers();
std::thread t1(&Broccoli::start_timers, this); //Launch a thread
t1.detach();
}
void start_timers()
{
_timer.execute();
}
The first time completes (I see the "completed" cout), but crashes at _t->execute(); inside the for loop with an EXEC_BAD_ACCESS. I added a cout to check the size of the vector and it is 2 so both timers are inside. I do see this in the console:
this Timers * 0xbfffd998
_timers std::__1::vector<Timer *, std::__1::allocator<Timer *> >
if I change the detach() to join() everything completes without the crash, but it blocks execution of my app until those timers finish.
Why are you using threads here? Timers::execute() calls execute on a timer, then waits for it to finish, then calls execute on the next, and so forth. Why don't you just call the timer function directly in Timers::execute() rather than spawning a thread and then waiting for it?
Threads allow you to write code that executes concurrently. What you want is serial execution, so threads are the wrong tool.
Update: In the updated code you run start_timers on a background thread, which is good. However, by detaching that thread you leave the thread running past the end of the scope. This means that the timer objects _g and _g1 and even the Timers object _timers are potentially destroyed before the thread has completed. Given the time-consuming nature of the timers thread, and the fact that you used detach rather than join in order to avoid your code blocking, this is certainly the cause of your problem.
If you run code on a thread then you need to ensure that all objects accessed by that thread have a long-enough lifetime that they are still valid when the thread accesses them. For detached threads this is especially hard to achieve, so detached threads are not recommended.
One option is to create an object containing _timers, _g and _g1 along side the thread t1, and have its destructor join with the thread. All you need to do then is to ensure that the object lives until the point that it is safe to wait for the timers to complete.
If you don't want to interfere with the execution of the program, you could do something like #Joel said but also adding a thread in the Timers class which would execute the threads in the vector.
You could include a unique_ptr to the thread in GrowingTimer instead of creating it as a local object in execute and calling detach. You can still create the thread in execute, but you would do it with a unique_ptr::reset call.
Then use join instead of isTimerComplete (add a join function to the Timer base class). The isTimerComplete polling mechanism will be extremely inefficient because it will basically use up that thread's entire time slice continually polling, whereas join will block until the other thread is complete.
An example of join:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void threadMain()
{
this_thread::sleep_for(chrono::seconds(5));
cout << "Done sleeping\n";
}
int main()
{
thread t(threadMain);
for (int i = 0; i < 10; ++i)
{
cout << i << "\n";
}
t.join();
cout << "Press Enter to exit\n";
cin.get();
return 0;
}
Note how the main thread keeps running while the other thread does its thing. Note that Anthony's answer is right in that it doesn't really seem like you need more than one background thread that just executes tasks sequentially rather than starting a thread and waiting for it to finish before starting a new one.

Pthread Passing Function to Pool

I am working on creating a threadpool from scratch as part of an assignment and am able to create the thread pool and then pass each created thread a function that constantly loops. My question is how can I accept the input and pass it to an already executing pthread. After figuring this out I will add mutexes to lock the function to a specific thread, but I am unable to get to that part.
class ThreadPool{
public:
ThreadPool(size_t threadCount);
int dispatch_thread(void *(dispatch_function(void *)), void *arg);
bool thread_avail();
int numThreads;
pthread_t * thread;
pthread_mutex_t * mutexes;
};
int ThreadPool::dispatch_thread(void *(dispatch_function(void *)), void *arg){
flag = 1;
//This is where I would like to pass the function the running pthread
}
void *BusyWork(void *t)
{
while(true){
//This is where I would like to run the passed function from each thread
//I can run the passed function by itself, but need to pass it to the threadpool
}
}
ThreadPool::ThreadPool(size_t threadCount){
pthread_t thread[threadCount];
for(t=0; t<threadCount; t++) {
//printf("Main: creating thread %ld\n", t);
rc = pthread_create(&thread[t], NULL, BusyWork, (void *)t);
}
}
void *test_fn(void *par)
{
cout << "in test_fn " << *(int *)par << endl;
}
int main (){
ThreadPool th(3);
int max = 100;
for (int i = 0; i < 20; i++) {
max = 100 * i;
th.dispatch_thread(test_fn, (void *)&max);
sleep(1);
}
}
The best pattern that I can think of is to use some sort of queue to pass messages to the thread-pool. These messages may contain functions to be run as well as some control messages for shutting down the thread-pool. As you already have guessed, the queue will have to be thread safe.
A simple approach for the queue is to use a fixed size array which you turn into a circular buffer. The array will have a Mutex to lock it when accessing the array and a Condition Variable to awaken the thread-pool thread.
When putting an item on the queue, we lock the mutex, add to the queue and then signal the thread-pool with the Condition Variable.
Each running thread in the in the thread pool will start life by locking the mutex and waiting on the condition varaible (which automaticall unlocks the Mutex). When awoken it will remove the item from the queue, and then unlock the mutex. It is now free do its stuff. When finished it goes to sleep until re-signaled.
As general advice, avoid sharing memory between threads because this either leads to race conditions (if access is not protected) or leads to interlocking (if access is locked). Also avoid locking a mutex when performing any long running operation such as calling new (malloc), delete (free) or any system calls.

c++ multithread

I use C++ to implement a thread class. My code shows in the following.
I have a problem about how to access thread data.
In the class Thread, I create a thread use pthread_create() function. then it calls EntryPoint() function to start thread created. In the Run function, I want to access the mask variable, it always shows segment fault.
So, my question is whether the new created thread copy the data in original class? How to access the thread own data?
class Thread {
public:
int mask;
pthread_t thread;
Thread( int );
void start();
static void * EntryPoint (void *);
void Run();
};
Thread::Thread( int a) {
mask =a;
}
void Thread::Run() {
cout<<"thread begin to run" <<endl;
cout << mask <<endl; // it always show segmentfault here
}
void * Thread::EntryPoint(void * pthis) {
cout << "entry" <<endl;
Thread *pt = (Thread *) pthis;
pt->Run();
}
void Thread::start() {
pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
pthread_join(thread, NULL);
}
int main() {
int input_array[8]={3,1,2,5,6,8,7,4};
Thread t1(1);
t1.start();
}
I'm not familiar with the libraries you're using, but how does EntryPoint know that pthis is a pointer to Thread? Thread (this) does not appear to be passed to pthread_create.
It's great that you're attempting to write a Thread class for educational purposes. However, if you're not, why reinvent the wheel?
pThis is most likely NULL, you should double check that you're passing the correct arguments to pthread_create.
Basically, the problem is as soon as you start your thread, main exits and your local Thread instance goes out of scope. So, because the lifetime of your thread object is controlled by another thread, you've already introduced a race condition.
Also, I'd consider joining a thread immediately after you've created it in Thread::start to be a little odd.