I am currently making intern and I am asked to write a multi client server-client application with using C++. Hence, I'm trying to learn threading. Have one question:
I want to print "you are in thread A", then "you are in thread B", "now you are again in thread A". However it only prints first two sentences and ignores endl command. Can't exactly understand how it works. How to fix that and could you briefly explain working mechanism?
Why main thread exits before all function calls completed?
void * function1(void * arg);
void * function2(void * arg);
pthread_t thr_A, thr_B;
int main( void )
{
pthread_create(&thr_A, NULL, function1, (void*)thr_B);
pthread_create(&thr_B, NULL, function2,NULL);
return 0;
}
void * function1(void * arg)
{
cout << "You are in thread A" << endl;
pthread_join(thr_B, NULL);
cout << "now you are again in thread A" << endl;
pthread_exit((void*)thr_A);
}
void * function2(void * arg)
{
cout << " you are in thread B " << endl ;
pthread_exit((void*)thr_B);
}
In you main function you create one race condition. The threads may be started in any order, unless you specifically synchronize your code so that you enforce one or the other to start.
Therefore it is also impossible to tell which will finish first. Then you also have your main thread, it might even finish before the threads you create finish. When using pthreads you must call pthread_join in order to wait for a thread to finish. You can do that like this:
int main( void )
{
// you pass thread thr_B to function one but
// function2 might even start before function1
// so this needs more syncronisation
pthread_create(&thr_A, NULL, function1, (void*)thr_B);
pthread_create(&thr_B, NULL, function2,NULL);
//this is mandatory to wait for your functions
pthread_join( thr_A, NULL);
pthread_join( thr_B, NULL);
return 0;
}
in order to wait in function1 you need more sophisticated synchronization method for example see for example pthread_cond_wait pthread_cond_signal as explained in: https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal
You also should remove the pthread_join from function one because according man pthread join: "If multiple threads simultaneously try to join with the same thread,
the results are undefined."
Edit on comment of David hammen:
void * function1(void * arg)
{
cout << "You are in thread A" << endl;
//Remove the next line and replace by a pthread_cond_wait.
pthread_join(thr_B, NULL);
cout << "now you are again in thread A" << endl;
pthread_exit((void*)thr_A);
}
Related
I am trying to learn multithreading in C++. I am trying to pass elements of a vector as arguments to pthread_create. However, it is not working as expected.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <vector>
using namespace std;
void *count(void *arg)
{
int threadId = *((int *)arg);
cout << "Currently thread with id " << threadId << " is executing " << endl;
pthread_exit(NULL);
}
int main()
{
pthread_t thread1;
vector<int> threadId(2);
threadId[0] = 99;
threadId[1] = 100;
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[0] << endl;
exit(-1);
}
pthread_t thread2;
retVal = pthread_create(&thread2, NULL, count, (void *)&threadId[1]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[1] << endl;
exit(-1);
}
pthread_exit(NULL);
}
The output which I get is:
Currently thread with id 99 is executing.
Currently thread with id 0 is executing
However, according to me, it should be:
Currently thread with id 99 is executing.
Currently thread with id 100 is executing.
What am I missing here ?
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]);
You have no guarantee, whatsoever, that the new execution thread is now running, right this very instant, without any delay.
All that pthread_create guarantees you is that the thread function, thread1, will begin executing at some point. It might be before pthread_create() itself returns. Or it might be at some point after. It's really a big mystery when the new thread function will start executing, but you can take it to the bank that the new execution thread will begin. Eventually.
The same thing goes for your 2nd execution thread.
So, both execution thread could very well get in gear after your main() returns, and after your vector gets destroyed. There's nothing in the shown code that guarantees that the execution threads will execute before the vector (whose contents get passed into them, in the manner shown) gets destroyed. And this leads to undefined behavior.
You will need to use other thread-related facilities that must be employed in order to synchronize multiple execution threads correctly. Additionally, you're using older POSIX threads. Modern C++ uses std::threads which offer many advantages over their predecessor, is completely type-safe (no ugly casts) and have numerous attributes that prevent common programming errors (however, in this instance std::threads also have no synchronization guarantee, this is usually the case with all typical execution thread implementations).
I am beginning to use the thread class.
In the main() thread below, an Example class is created.
Inside the constructor of Example, two threads are created in the Example::start() function.
Example::foo() is designed to print a message every second.
Example::bar() is designed to print a message every 5 seconds.
Inside the main() function, a loop is designed to print every 3 seconds.
I decided to not use join() in Example::start() because I would like to have the main() function continuously run.
Why does the main thread crash during run-time?
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono> // std::chrono::seconds
using namespace std;
class Example
{
public:
Example();
void start();
void foo();
void bar(int x);
};
Example::Example()
{
start();
}
void Example::start()
{
std::thread first (&Example::foo, this); // spawn new thread that calls foo()
std::thread second (&Example::bar, this, 5); // spawn new thread that calls bar(0)
// synchronize threads:
//first.join(); // pauses until first finishes
//second.join(); // pauses until second finishes
}
void Example::foo()
{
cout << "entered foo()" << endl;
int count = 0;
while(1) {
std::this_thread::sleep_for (std::chrono::seconds(1));
++count;
cout << "foo() count = " << count << endl;
}
}
void Example::bar(int x)
{
cout << "entered bar() x = " << x << endl;
int count = 0;
while(1) {
std::this_thread::sleep_for (std::chrono::seconds(5));
++count;
cout << "bar() count = " << count << endl;
}
}
int main() {
Example* c = new Example();
cout << "Example() created" << endl;
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(3));
cout << "main() thread loop..." << endl;
}
std::cout << "end of main()";
delete c;
return 0;
}
Foo::Start() initalizes two threads, thread Foo and thread bar. When the function Start returns to the main thread, the two thread objects go out of scope and the destructor is called for clearing out of scope variables.
A simple solution would be to make threads part of the class.
On another note, std::cout is not a synchronized class, when writing your text might be garbled: Is cout synchronized/thread-safe?
Also, when creating your class Example, delete is never called which causes a memory leak.
Your comment here:
void Example::start()
{
std::thread first (&Example::foo, this); // spawn new thread that calls foo()
std::thread second (&Example::bar, this, 5); // spawn new thread that calls bar(0)
// synchronize threads:
//first.join(); // pauses until first finishes
//second.join(); // pauses until second finishes
}
Is wrong.
Not only does the the join pause until the threads finish. But they also allow the thread to be cleaned up. A thread destructor calls terminate while the thread is join-able (ie it is still running). So you must call join() on the thread (to wait for it to finish) before you can allow the destructor to be called.
One of the comments above suggests calling detach(). This detaches the thread of execution from the thread object (thus making it not join-able). This will work (as your code is in infinite loop), but is a bad idea generally. As allowing main() to exit while threads are still running is undefined behavior.
I want to know how to run a thread to sleep some time every time I press a key. For example, if I press the same key twice, it should have two threads to sleep for a while.
I MUST use pthreads and C++.
Honestly I have tried many ways but I still do not know how to solve it.
Sorry if my english is not very good :)
UPDATE
This is my code:
#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;
pthread_mutex_t mutex;
pthread_cond_t cond;
int a;
void* executer2(void*)
{
pthread_mutex_lock(&mutex);
while (a > 0) {
pthread_cond_wait(&cond, &mutex);
}
cout << "Thread: " << pthread_self() << endl;
sleep(a);
pthread_mutex_unlock(&mutex);
}
void* executer(void*)
{
int key;
while (1) {
pthread_mutex_lock(&mutex);
key = cin.get();
if (key == 'a') {
cout << "Sleep for 4 seconds" << endl;
a = 4;
} else if (key == 'b') {
cout << "Sleep for 8 seconds" << endl;
a = 8;
} else {
cout << "Sleep for 2 seconds" << endl;
a = 2;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t tr, t;
pthread_attr_t attr;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&tr, &attr, executer, NULL);
pthread_create(&t, &attr, executer2, NULL);
pthread_join(tr, NULL);
pthread_join(t, NULL);
}
since you want to create a thread each time you press a key, and that the keypress handler is in executer, you should move the code to create executer2 in executer.
executer is made to sleep 1 sec. after reading a key press, but it seems that's not what you want. Just remove that call to sleep(1) to get an immediate response
the code of executer seems to indicate that you wish to modulate the time spent sleeping by the thread depending on the input key. You can pass the sleep time as a parameter to executer2, as indicated by the void * parameter of that function. The idea is to cast the time value to a void *, pass it at thread creation time, and cast it back to int within executer2:
// executer2 thread creation
pthread_create(&t, &attr, executer2,(void *)a);
and in executer2:
void *executer2(void *arg){
int a = (int)arg;
// ...
The thread creation code should go after the switch in executer2, and you should not need the global a variable anymore.
you are currently using a mutex to lock the code of executer2. This will prevent all the sleeping threads to sleep together at the same time. You will have to remove the lock to allow them to sleep concurrently (but leave the lock around the text output).
you say that you wish a C++ solution. You could benefit from using the thread library from the stl, which wraps the OS thread primitives (pthreads in your case) with higher level constructs and are easier to manipulate, especially for parameters. It would be a good exercise to convert your programme to use this library once you have the current code working.
I am working in a C++ DLL module where I need to perform a task for every X min independently. I tried to create a thread for the task but my main program which creates threads will also keep waiting for the child thread(s) to complete.
Could someone please help me how to create a separate process (Please provide sample code if possible) independent of main program and do the Task?
The process should take a function and run the code present in function for every X min.
EDIT:
void test(void *param)
{
cout << "In thread function" << endl;
Sleep(1000); // sleep for 1 second
cout << "Thread function ends" << endl;
_endthread();
}
int main()
{
HANDLE hThread;
cout << "Starting thread" << endl;
cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
WaitForSingleObject( hThread, INFINITE );
cout << "Main ends" << endl;
return 0;
}
WaitForSingleObject() will block main until the thread completes. If you want to run some stuff periodically from the thread function test() you'll need to put a loop there. Best with some condition to trigger ending the thread function from main() when exiting. You shouldn't call WaitForSingleObject() before you want to exit the main() method. Thus you'll have the test() method running asynchonously.
bool endThread = false;
void test(void *param)
{
cout << "In thread function" << endl;
while(!endThread)
{
Sleep(1000); // sleep for 1 second
}
cout << "Thread function ends" << endl;
_endthread();
}
int main()
{
HANDLE hThread;
cout << "Starting thread" << endl;
cout << (hThread = (HANDLE)_beginthread(test,0,NULL));
// Do any other stuff without waiting for the thread to end
// ...
endThread = true;
WaitForSingleObject( hThread, INFINITE );
cout << "Main ends" << endl;
return 0;
}
Note that you might need to synchronize access to the endThread variable properly using a mutex or similar, the sample should just show the principle.
UPDATE:
In case you want to exit main() before the thread ends, you cannot use threads at all.
You'll need to create an independent child process as I had mentioned in my 1st comment. Lookup for the fork() and exec() functions to do this (there might be specific WinAPI methods for these also, I don't know about).
Hey - I'm having an odd problem with a little toy program I've written, to try out threads.
This is my code:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
void *threadFunc(void *arg) {
cout << "I am a thread. Hear me roar." << endl;
pthread_exit(NULL);
}
int main() {
cout << "Hello there." << endl;
int returnValue;
pthread_t myThread;
returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);
if (returnValue != 0) {
cout << "Couldn't create thread! Whoops." << endl;
return -1;
}
return 0;
}
With the first cout in main not commented out, the thread prints fine.
However, without it, the thread doesn't print anything at all.
Any help?
Try this:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
void *threadFunc(void *arg) {
cout << "I am a thread. Hear me roar." << endl;
pthread_exit(NULL);
}
int main() {
//cout << "Hello there." << endl;
int returnValue;
pthread_t myThread;
returnValue = pthread_create(&myThread, NULL, threadFunc, NULL);
if (returnValue != 0) {
cout << "Couldn't create thread! Whoops." << endl;
return -1;
}
pthread_join( myThread, NULL);
return 0;
}
The difference between my code and yours is one line - pthread join. This suspends the main thread until the sub-thread has had chance to complete its actions.
In your code, execution reaches the first cout and it's processed. Then, you split off another thread and the main thread carries on until the end, which may or may not be reached before the secondary thread is tidied up. That's where the odd behaviour comes in - what you are experiencing is the case where the main program finishes before the sub-thread has had a chance to, so the program has "returned" and the whole lot is cleaned up by the kernel.
It's a race condition that allows the program to work when the main loop takes a little while to run. Your program is exiting before the thread even has a chance to run.
You should wait for the thread to complete (see pthread_join) before returning from main().
The fact that it works in one case is pure luck. You have a timing issue, which is your program is exiting before your thread does it's work.
When main() exits all your threads will die. You need some sort of waiting in place to give the other thread time to run before main() exits. Try adding a cin in main() after you create the worker thread and see what happens.
Ultimately you'll want some sort of run-loop and messaging/eventing to communicate between threads.
-jeff
Try adding a pthread_exit(NULL); at the end of main, before the return 0. I suspect that the problem is your main returns and the process exits before the thread has a chance to print. Printing from main might be somehow modifying the timing such that the thread does get a chance to print -- but that's is just sheer luck. You need to ensure that main doesn't return until all of your threads are finished doing their work. Calling pthread_exit from main allows other threads to continue running until they too have called pthread_exit.