Reputation: 2028
I want to run some jobs in parallel inside a single process. For some reason the thread I've created runs only once, please help me understand where is my mistake.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void * print_thread (void * var)
{
int *p_var = (int *)var;
printf("this is a thread %d\n", ++(*p_var));
}
int main()
{
int x=0;
pthread_t thread1;
if(pthread_create(&thread1, NULL, print_thread, &x))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}
while (1)
{
usleep(100000);
}
return 0;
}
# gcc -o thread pthread_example.c -lpthread
# ./thread
this is a thread 1
Upvotes: 0
Views: 1031
Reputation: 7798
You should think of print_thread as your new threads "main". It will run from start to finish and then the thread will exit. Unless you have some kind of loop inside of print_thread, it will never persist.
Upvotes: 2