Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C thread creation in a 20 line program. Why doesn't it work?

I'm trying to run a short program that creates three threads within a for loop, each of them writing "inside" to the screen. This is happening with Cygwin running on both XP and Vista on different machines. This is the current code.

#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
void* printInside(void* arg);

int main()
{
    pthread_t threads[3];
    for(int i = 0; i < 3; i++)
    {
        pthread_create(&threads[i], 0, printInside, 0);
    }
    return 0;
}
void* printInside(void* arg)
{
    cout << "inside";
        return 0;
}

And it doesn't work. If I add a cout to the inside of the for loop, it appears to slow it down into working.

for(int i = 0; i < 3; i++)
{
    cout << "";
    pthread_create(&threads[i], 0, printInside, 0);
}

Any suggestions as to why this is the case?

EDIT:

I've gotten responses to add a join after the loop

int main()
 {
     pthread_t threads[3];
     for(int i = 0; i < 3; i++)
    {
        pthread_create(&threads[i], 0, printInside, 0);
    }
     for(int i = 0; i < 3; i++)
    {
        void* result;
        pthread_join(threads[i],&result);
    }
}
 void* printInside(void* arg)
 {
    cout << "inside";
    return 0;
}

But it still doesn't work, is the join done wrong?

FIXED

"Output is usually buffered by the standard library. It is flushed in certain circumstances but sometimes you have to do it manually. So even if the threads run and produce output you won't see it unless you flush it."

like image 560
wsnarski Avatar asked Feb 03 '23 05:02

wsnarski


2 Answers

You need to join or the main thread will just exit:

for(int i = 0; i < 3; i++)
{
    pthread_create(&threads[i], 0, printInside, 0);
}
/* Join here. */

If I add a cout to the inside of the for loop, it appears to slow it down into working.

Doing I/O is generally hard and slow. This gives the other threads enough CPU time to run.

Remember, when using multiple threads if one calls exit they all die.

EDIT

adding an endl to the end of "inside" does make it work better, but it seems like a cop-out solution. Just wondering why it would be necessary even with the join present.

Output is usually buffered by the standard library. It is flushed in certain circumstances but sometimes you have to do it manually. So even if the threads run and produce output you won't see it unless you flush it.

like image 149
cnicutar Avatar answered Feb 04 '23 20:02

cnicutar


  • You start all threads without any wait, and exit the main thread (thus the whole program) before they start executing.

  • Calling pthread_join before return will wait for the other threads to finish.

  • The cout helps, as it generates a context switch and a window to the other threads to run.

like image 34
MByD Avatar answered Feb 04 '23 18:02

MByD