SCG
SCG

Reputation: 21

Why isn't the program waiting for the pthread

The program isn't executing the whole for-loop of function 1. I thought joining the thread would make the program wait for the tread to end.

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* func1(void* arg) {
    for(int i=0;i<10;i++) {
        printf("Func 1: %d\n", i);
        sleep(1);
    }
    return NULL;
}

void func2(void) {
    for(int i=0;i<5;i++) {
        printf("Func 2: %d\n", i);
        sleep(1);
    }
}

int main(void) {
    pthread_t new_thread;
    pthread_create(&new_thread, NULL, func1, NULL);
    func2();
    pthread_join(&new_thread, NULL);
    return 0;
}

Upvotes: 1

Views: 62

Answers (2)

user3629249
user3629249

Reputation: 16540

The following proposed code:

  1. cleanly compiles
  2. performs the desired functionality
  3. note the use of appropriate horizontal and vertical spacing for readability by us humans
  4. note the preferred method of exiting a thread.

And now, the proposed code:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>


void* func1( void* arg ) 
{
    (void)arg;  // to avoid compiler warning about unused parameter
    
    for( int i=0; i<10; i++ ) 
    {
        printf( "Func 1: %d\n", i );
        sleep(1);
    }
    pthread_exit( NULL );
}


void func2( void ) 
{
    for( int i=0; i<5; i++ ) 
    {
        printf( "Func 2: %d\n", i );
        sleep(1);
    }
}


int main( void ) 
{
    pthread_t new_thread;
    pthread_create( &new_thread, NULL, func1, NULL );
    func2();
    pthread_join( new_thread, NULL );
    return 0;
}

A typical run of the proposed code results in:

Func 2: 0
Func 1: 0
Func 2: 1
Func 1: 1
Func 2: 2
Func 1: 2
Func 2: 3
Func 1: 3
Func 2: 4
Func 1: 4
Func 1: 5
Func 1: 6
Func 1: 7
Func 1: 8
Func 1: 9

Upvotes: 1

P.P
P.P

Reputation: 121347

From pthread_join:

   int pthread_join(pthread_t thread, void **retval);

As you can see, the first arugment is a pthread_t but you're passing pthread_t* - that's the issue. So you should use:

pthread_join(new_thread, NULL);

Note that if you have error checked the pthread_* function calls, you'd have found the problem. For example, run your code with:

errno = pthread_join(&new_thread, NULL);
if (errno) perror("pthread_join");

and see what it says.

Similarly, enabling compiler warnings (such as -Wall -Wextra) would help, too.

Upvotes: 5

Related Questions