make main program wait for threads to finish - c++

In the following code I create some number of threads, and each threads sleeps for some seconds.
However my main program doesn't wait for the threads to finish, I was under the assumption that threads would continue to run until they finished by themselves.
Is there someway of making threads continue to run even though the calling thread finishes.
#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
int sample(int min,int max){
int r=rand();
return (r %max+min );
}
void *worker(void *p){
long i = (long) p;
int s = sample(1,10);
fprintf(stdout,"\tid:%ld will sleep: %d \n",i,s);
sleep(s);
fprintf(stdout,"\tid:%ld done sleeping \n",i,s);
}
pthread_t thread1;
int main(){
int nThreads = sample(1,10);
for(int i=0;i<nThreads;i++){
fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
pthread_detach(thread1);
}
// sleep(10);//work if this is not commented out.
return 0;
}
Thanks
Edit:
Sorry for not clarifying, is it possible without explicitly keeping track of my current running threads and by using join.

Each program has a main thread. It is the thread in which your main() function executes. When the execution of that thread finishes, the program finishes along with all its threads. If you want your main thread to wait for other threads, use must use pthread_join function

You need to keep track of the threads. You are not doing that because you are using the same thread1 variable to every thread you are creating.
You track threads by creating a list (or array) of pthread_t types that you pass to the pthread_create() function. Then you pthread_join() those threads in the list.
edit:
Well, it's really lazy of you to not keep track of running threads. But, you can accomplish what you want by having a global var (protected by a mutex) that gets incremented just before a thread finishes. Then in you main thread you can check if that var gets to the value you want. Say nThreads in your sample code.

You need to join each thread you create:
int main()
{
int nThreads = sample(1,10);
std::vector<pthread_t> threads(nThreads);
for(i=0; i<nThreads; i++)
{
pthread_create( &threads[i], NULL, worker, (void*) i)
}
/* Wait on the other threads */
for(i=0; i<nThreads; i++)
{
status* status;
pthread_join(threads[i], &status);
}
}

You learned your assumption was wrong. Main is special. Exiting main will kill your threads. So there are two options:
Use pthread_exit to exit main. This function will allow you to exit main but keep other threads running.
Do something to keep main alive. This can be anything from a loop (stupid and inefficient) to any blocking call. pthread_join is common since it will block but also give you the return status of the threads, if you are interested, and clean up the dead thread resources. But for the purposes of keeping main from terminating any blocking call will do e.g. select, read a pipe, block on a semaphore, etc.
Since Martin showed join(), here's pthread_exit():
int main(){
int nThreads = sample(1,10);
for(int i=0;i<nThreads;i++){
fprintf(stderr,"\t-> Creating: %d of %d\n",i,nThreads);
int iret1 = pthread_create( &thread1, NULL, worker, (void*) i);
pthread_detach(thread1);
}
pthread_exit(NULL);
}

Related

How to make two threads take turns executing their respective critical sections after one thread ends

In modern C++ with STL threads I want to have two worker threads that take turns doing their work. Only one can be working at a time and each may only get one turn before the other takes a turn. I have this part working.
The added constraint is that one thread needs to keep taking turns after the other thread finishes. But in my code the remaining worker thread deadlocks after the first worker thread finishes. I don't understand why, given that the last things the first worker did was unlock and notify the condition variable, which should've woken the second one up. Here's the code:
{
std::mutex mu;
std::condition_variable cv;
int turn = 0;
auto thread_func = [&](int tid, int iters) {
std::unique_lock<std::mutex> lk(mu);
lk.unlock();
for (int i = 0; i < iters; i++) {
lk.lock();
cv.wait(lk, [&] {return turn == tid; });
printf("tid=%d turn=%d i=%d/%d\n", tid, turn, i, iters);
fflush(stdout);
turn = !turn;
lk.unlock();
cv.notify_all();
}
};
auto th0 = std::thread(thread_func, 0, 20);
auto th1 = std::thread(thread_func, 1, 25); // Does more iterations
printf("Made the threads.\n");
fflush(stdout);
th0.join();
th1.join();
printf("Both joined.\n");
fflush(stdout);
}
I don't know whether this is something I don't understand about concurrency in STL threads, or whether I just have a logic bug in my code. Note that there is a question on SO that's similar to this, but without the second worker having to run longer than the first. I can't find it right now to link to it. Thanks in advance for your help.
When one thread is done, the other will wait for a notification that nobody will send. When only one thread is left, you need to either stop using the condition variable or signal the condition variable some other way.

C++ threads add two array to one result array [duplicate]

I'm fairly new to threads in C. For this program I need to declare a thread which I pass in a for loop thats meant to print out the printfs from the thread.
I can't seem to get it to print in correct order. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 16
void *thread(void *thread_id) {
int id = *((int *) thread_id);
printf("Hello from thread %d\n", id);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
int code = pthread_create(&threads[i], NULL, thread, &i);
if (code != 0) {
fprintf(stderr, "pthread_create failed!\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
//gcc -o main main.c -lpthread
That's the classic example of understanding multi-threading.
The threads are running concurrently, scheduled by OS scheduler.
There is no such thing as "correct order" when we are talking about running in parallel.
Also, there is such thing as buffers flushing for stdout output. Means, when you "printf" something, it is not promised it will happen immediately, but after reaching some buffer limit/timeout.
Also, if you want to do the work in the "correct order", means wait until the first thread finishes it's work before staring next one, consider using "join":
http://man7.org/linux/man-pages/man3/pthread_join.3.html
UPD:
passing pointer to thread_id is also incorrect in this case, as a thread may print id that doesn't belong to him (thanks Kevin)

Threads in for loop not working correctly

I want to make a program that gets the ids from a database and create a thread with the same function for each id. It works, but when I add a while loop to the function it only hangs there and doesn't get the next id's.
My code is:
void foo(char* i) {
while(1){
std::cout << i;
}
}
void makeThreads()
{
int i;
MYSQL *sqlhnd = mysql_init(NULL);
mysql_real_connect(sqlhnd, "127.0.0.1", "root", "h0flcepqE", "Blazor", 3306, NULL, 0);
mysql_query(sqlhnd, "SELECT id FROM `notifications`");
MYSQL_RES *confres = mysql_store_result(sqlhnd);
int totalrows = mysql_num_rows(confres);
int numfields = mysql_num_fields(confres);
MYSQL_FIELD *mfield;
MYSQL_ROW row;
while((row = mysql_fetch_row(confres)))
{
for(i = 0; i < numfields; i++)
{
printf("%s", row[i]);
std::thread t(foo, row[i]);
t.join();
}
}
}
int main()
{
makeThreads();
return 0;
}
Output is:
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
Thanks
The for loop in question currently creates one thread object and one thread. Period. joining hides this problem in a way by forcing the main thread to wait for the thread to run to completion. That the thread can't is another issue.
Creating a thread and immediately joining forces your program to run sequentially and defeats the point of using threads. Not joining the thread will result in Bad because the thread object will be destroyed at the end of the loop and the thread has not been detached. Destroying an undetached thread is bad. std::terminate does pretty much what it sounds like it does: It hunts down and kills Sarah Connor. Just kidding. It ends your program with all the subtlety of a headsman's axe.
You could detach the threads manually by calling detach, but that's a really, really Bad Idea because you lose control of the thread and your program will exit while the threads are still running.
You need to store these threads and join them later, after the loop that spawns them.
Here's a simple approach to do that:
std::vector<std::thread> threads;
for(i = 0; i < numfields; i++)
{
std::cout << row[i];
threads.push_back(std::thread(foo, row[i]));
}
for (std::thread & t: threads)
{
t.join();
}
Now you will have numfields threads running forever, and I'm sure you can take care of that problem on your own.
t.join();
Means the program waits here for the thread t to finish.
Since:
t executes foo
foo never ends, due to while true
Then: you never execute the instructions after the join
So you have the uninterrupted 111111

Linux Multithreading - threads do not produce any output as expected

I am learning multi-threading in Linux platform. I wrote this small program to get comfort with the concepts. On running the executable, I could not see any error nor does it print Hi. Hence I made to sleep the thread after I saw the output. But still could not see the prints on the console.
I also want to know which thread prints at run time. Can anyone help me?
#include <iostream>
#include <unistd.h>
#include <pthread.h>
using std::cout;
using std::endl;
void* print (void* data)
{
cout << "Hi" << endl;
sleep(10000000);
}
int main (int argc, char* argv[])
{
int t1 = 1, t2 =2, t3 = 3;
pthread_t thread1, thread2, thread3;
int thread_id_1, thread_id_2, thread_id_3;
thread_id_1 = pthread_create(&thread1, NULL, print, 0);
thread_id_2 = pthread_create(&thread2, NULL, print, 0);
thread_id_3 = pthread_create(&thread3, NULL, print, 0);
return 0;
}
Your main thread probably exits and thus the entire process dies. So, the threads don't get a chance to run. It's also possible (quite unlikely but still possible) that you'd see the output from the threads even with your code as-is if the threads complete execution before main thread exits. But you can't rely on that.
Call pthread_join(), which suspends the calling thread until the thread (specified by the thread ID) returns, on the threads after the pthread_create() calls in main():
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
You can also use an array of pthread_t which would allow you to use a for loop over the pthread_create() and pthread_join() calls.
Or exit only the main thread using pthread_exit(0), which would exit only the calling thread and the remaining threads (the ones you created) will continue execution.
Note that your thread function should return a pointer or NULL:
void* print (void* data)
{
cout << "Hi" << endl;
return NULL;
}
Not sure about the high sleeps either right the threads exit, which is unnecessary and would hold the threads from exiting. Probably not something you wanted.

Does or does not pthread_join() allow execution on calling thread to continue?

edit:
I made the wrong assumption that threads started running on pthread_join when they actually start running on pthread_create.
I'm learning to use Posix threads, and I've read that:
pthread_join() - wait for thread termination
So, in the code sample, main's exit(0) is not reached until both started threads end.
But after the first call to pthread_join(), main continues executing, because the second call to pthread_join() actually runs, and the message in between is printed.
So how's this? does main continue executing while both threads aren't finished yet? or doesn't it?
I know this isn't a reliable way of testing, but the second test message always gets printed after both threads are finished, no matter how long the loop is. (at least on my machine when I tried it)
void *print_message_function( void *ptr )
{
char *message = (char *) ptr;
for( int a = 0; a < 1000; ++a )
printf( "%s - %i\n", message, a );
return NULL;
}
//
int main( int argc, char *argv[] )
{
pthread_t thread1, thread2;
char message1[] = "Thread 1";
char message2[] = "Thread 2";
int iret1, iret2;
//
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
//
pthread_join( thread1, NULL);
printf( "Let's see when is this printed...\n" );
pthread_join( thread2, NULL);
printf( "And this one?...\n" );
//
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
The function pthread_join waits for the thread to finish or returns immediately if the thread is already done.
So in your case
pthread_join( thread1, NULL); /* Start waiting for thread1. */
printf( "Let's see when is this printed...\n" ); /* Done waiting for thread1. */
pthread_join( thread2, NULL); /* Start waiting for thread2. */
printf( "And this one?...\n" ); /* Done waiting for thread2. */
But after the first call to pthread_join(), main continues executing,
because the second call to pthread_join() actually runs, and the
message in between is printed.
False. pthread_join waits unless thread1 is already done.
pthread_join() does not return (blocking the calling thread) until the thread being joined has terminated. If the thread has already terminated, then it returns straight away.
In your test, both threads do exit, and so of course you'll see all the messages printed from the main thread. When the first message is printed, you know that thread1 is complete; when the second is printed you know that thread2 is also complete. This will probably happen quite quickly after the first, since both threads were doing the same amount of work at roughly the same time.
pthread_join( thread1, NULL);
The main thread waits here on this join call till thread1 completes its job. Once thread1 completes execution main thread will proceed ahead and execute the next statement printf.
printf( "Let's see when is this printed...\n" );
Again, Main thread will wait here till thread2 completes its job.
pthread_join( thread2, NULL);
Once thread2 completes its job the main thread moves ahead and the next statement which is the printf is executed.
printf( "And this one?...\n" );
The sequence will work in the above mentioned way.Probably, this happens all too soon that the traces you see makes it confusing.
Also, Do not using printf to see behavior of multithreaded programs can be quite misleading, the order of the printf may not always indicate the correct control flow Since it is timing based and flushing of the buffers to stdout may not happen in sasme order as the prints were executed accross threads.
If the first pthread_join returns immediately, that would suggest that the first thread has already finished executing. What does the output look like? Do you see any "Thread 1 - n" output after "Let's see when this is printed"?