Talen Kylon
Talen Kylon

Reputation: 1958

Threads in c, what am I missing here?

I'm trying to create a thread, and I cannot figure out what I am doing wrong here. It's very basic, I just want to make sure I can get the thread created before I delve into what I'll be doing in the thread. Here's my code.

//prog.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <pthread.h>
#include <stdbool.h>
#include <unistd.h>

int threadCount =0; //Global variable to hold our thread counter 

//this is the function that gets called when a thread is created
void *threadCreate(void* arg){
    printf("Thread #%d has been created\n", threadCount);
    threadCount++;
    int param = (int)arg;

    printf("We were sent: %d\n", param);
    printf("Now the thread will die\n");
    threadCount--;
    pthread_exit(NULL);
}

//main
int main(int argc, char *argv[]){
    pthread_t tid;
    int numski = 50;
    int res;
    res = pthread_create(&tid, NULL, threadCreate, (void*)numski);
    if (res){
        printf("Error: pthread_create returned %d\n", res);
        exit(EXIT_FAILURE); 
    }
    return 0;
}

I am compiling using the following command:

gcc -Wall -pthread -std=c99 prog.c -o Prog

And when I try to run it, I get no output at all.

Upvotes: 0

Views: 504

Answers (1)

djechlin
djechlin

Reputation: 60748

Main is exiting right away, and therefore your process is dying right away. End it with pthread_join to wait for them. Here is one example I googled, which contains the following example code:

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

void *print_message_function( void *ptr );

main()
{
     pthread_t thread1, thread2;
     const char *message1 = "Thread 1";
     const char *message2 = "Thread 2";
     int  iret1, iret2;

    /* Create independent threads each of which will execute function */

     iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
     iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

     /* Wait till threads are complete before main continues. Unless we  */
     /* wait we run the risk of executing an exit which will terminate   */
     /* the process and all threads before the threads have completed.   */

     pthread_join( thread1, NULL);
     pthread_join( thread2, NULL); 

     printf("Thread 1 returns: %d\n",iret1);
     printf("Thread 2 returns: %d\n",iret2);
     exit(0);
}

void *print_message_function( void *ptr )
{
     char *message;
     message = (char *) ptr;
     printf("%s \n", message);
}

Upvotes: 3

Related Questions