Thread immediately executes after pthread_create? - c

When I'm creating T threads, I have the following code in the main thread.
pthread_t threads[T];
for (a=0; a<T; a++) {
pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");
It creates the first thread, and I noticed that it immediately begins executing the first thread. foo is called for the first thread and "in main thread" gets outputed after. My actual intent was to create all T threads first (pushing the threads into a 'ready' queue) and then continue executing code in the main thread until it exits or yields. Once main exits, I want one of the T threads to execute.
In foo function:
void foo(pthread_t *threads, pthread_mutex_t **locks, double **transition) {
printf("in foo\n");
}
In the main_thread function:
void main_thread (int *N, int *T) {
double **transition;
pthread_mutex_t **locks;
transition = malloc(*N * sizeof *transition);
locks = malloc(*N * sizeof *locks);
for (a=0; a< *N; a++) {
transition[a] = malloc(*N * sizeof *transition[a]);
locks[a] = malloc(*N * sizeof *locks[a]);
}
// lock for each element in transition matrix
for (a=0; a<*N; a++) {
for (b=0; b<*N; b++) {
if (pthread_mutex_init(&(locks[a][b]), NULL) != 0) {
printf("\n mutex init has failed\n");
}
}
}
for (a=0; a<*N; a++) {
for (b=0; b<*N; b++) {
transition[a][b] = 0.0;
}
}
pthread_t threads[T];
for (a=0; a<T; a++) {
pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");
}
In the main function:
int main(int argc, char *argv[]) {
int N = 4;
int T = 2;
pthread_t main_t;
pthread_create(&main_t, NULL, &main_thread(&N, &T), NULL);
return 0;
}

With foo(...) you call the function, passing the result of it to the pthread_create function. That means the function will execute before any thread is created.
You need to pass a pointer to the thread function instead:
pthread_create(&threads[a], NULL, foo, NULL);
Also note that when the main function exits, it usually leads to the whole process exiting and that will kill all threads you have started.
If you want to keep threads running after you exit the main thread then you need to use pthread_exit from the main thread, and detach the threads you create.
And to not start the threads at once, IIRC there are attributes you can set and pass to the pthread_create function (the second argument) to start the threads as suspended. You have to explicitly resume the threads though, that won't happen automatically.

Related

why does Pthread Signal from main, hangs the code?

The requirement for the sample application creating using pthread is given below:
A single thread is created from main using Pthread
Inside thread, Mutex is locked, a counter counts the value and while loop is incremented, While is set to the max count of 10.
after while loop finishes, the mutex is unlocked.
The above requirement I have tried implementing using pthread
Code is shown below:
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
int samples = 10;
int count = 0;
struct example
{
int i;
int a;
};
void *inc_x(void *x_void_ptr)
{
pthread_mutex_lock(&count_mutex);
printf("Thread is locked \n");
while(count < samples)
{
printf("inside While loop \n");
struct example *E2_ptr;
E2_ptr = (struct example *)x_void_ptr;
printf("inside thread count = %d\n",count);
E2_ptr->a = count;
E2_ptr->i = (count + 1);
count ++;
//pthread_cond_wait(&count_threshold_cv, &count_mutex);
}
pthread_mutex_unlock(&count_mutex);
printf ( "\n Test Successful for Thread\n");
pthread_exit(NULL);
}
int main()
{
int x = 100, y = 0,i = 0;
struct example *E1_ptr;
E1_ptr->a = 0;
E1_ptr->i = 0;
printf("Before\t E1_ptr->a = %d\t, E1_ptr->i = %d\n",E1_ptr->a,E1_ptr->i);
pthread_t inc_x_thread;
if(pthread_create(&inc_x_thread, NULL, inc_x, E1_ptr))
{
printf("Error creating thread\n");
}
if(pthread_join(inc_x_thread, NULL))
{
printf("Error joining thread\n");
}
for(i = 0; i<(samples-1); i++)
{
if(pthread_cond_signal(&count_threshold_cv))
{
printf("Error Signaling thread at sample = %d\n",i);
}
}
printf("after\t E1_ptr->a = %d\t, E1_ptr->i = %d\n",E1_ptr->a,E1_ptr->i);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (NULL);
return 0;
}
Doubt:
In the above code, the thread executes its function properly and exits.
Once the condition is applied, i.e. the below shown code is uncommented then,
pthread_cond_wait(&count_threshold_cv, &count_mutex);
Then the thread is stopped after 1st iteration of while loop as expected.
The signal is generated from main by the code shown below:
for(i = 0; i<(samples-1); i++)
{
if(pthread_cond_signal(&count_threshold_cv))
{
printf("Error Signaling thread at sample = %d\n",i);
}
}
observed that the signal is never sent.
Can someone please guide me, where am I going wrong. I'm a newbie to Pthreads.
Thanks in advance.
count_mutex and count_threshold_cv are not initialized, add:
int main()
{
pthread_mutex_init(&count_mutex, NULL);
pthread_cond_init(&count_threshold_cv, NULL);
//...
E1_ptr is not initialized.
There are many ways to solve it:
You can call malloc to allocate memory:
struct example *E1_ptr = malloc(sizeof(struct example));
E1_ptr->a = 0;
E1_ptr->i = 0;
or holds pointer to local variable:
struct example ex;
struct example *E1_ptr = &ex; //malloc(sizeof(struct example));
E1_ptr->a = 0;
E1_ptr->i = 0;
or
struct example ex;
ex.a = 0;
ex.i = 0;
then create thread with pthread_create(&inc_x_thread, NULL, inc_x, &ex)
pthread_cond_signal function does not wait. If a thread is blocked by condition variable pthread_cond_signal function unblocks this thread, otherwise returns immediately without waiting and does nothing. So your for loop with 10 iterations is executed as soon as possible, without any waiting for pthread_cond_wait is called.
So can rewrite your for loop to infinite loop, calling pthread_cond_signal repeatedly.
if(pthread_create(&inc_x_thread, NULL, inc_x, E1_ptr)) {
printf("Error creating thread\n");
}
while(1) { // INFINITE LOOP
if(pthread_cond_signal(&count_threshold_cv)) {
printf("Error Signaling thread at sample = %d\n",i);
}
if (taskDone) // testing global flag, if 1 break
break; // it means inc_x thread has ended
}
if(pthread_join(inc_x_thread, NULL)) { // it was pointed out in comment
printf("Error joining thread\n"); // you need to join at the end of main function
}
taskDone is global int, with 0 as default value. It is set to 1 before pthread_exit is called in inc_x function. Setting/checking taskDone should be wrapped with some synchronization mechanism, for example by adding new mutex or use count_mutex.

two threads, first adds second substracts

This is a classic example of mutex locks. I don't know why the following code doesn't work, ie. it doesn't print "ctr = 0" every time (but, for example, ctr = 535).
int ctr;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void * add (void * arg_wsk)
{
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock (&m);
ctr++;
pthread_mutex_unlock (&m);
}
return(NULL);
}
void * sub(void * arg_wsk)
{
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock (&m);
ctr--;
pthread_mutex_unlock (&m);
}
return(NULL);
}
int main()
{
pthread_t tid1, tid2;
int i;
void *res;
ctr = 0;
pthread_mutex_init(&m, NULL);
pthread_create(&tid1, NULL, add, NULL);
pthread_detach(tid1);
pthread_create(&tid2, NULL, sub, NULL);
pthread_detach(tid2);
pthread_join(tid1, &res);
pthread_join(tid2, &res);
pthread_mutex_destroy(&m);
printf("ctr = %d", ctr);
pthread_exit(NULL);
}
I think you are misusing the POSIX API. If you detach the threads, you shouldn't join them. Remove the detach and see if this improves things. I think you'll see that main() now blocks until the threads have completed.
Note also, from the link for the join call
ESRCH No thread could be found corresponding to that specified by the
given thread ID.
If you're lucky, you'll hit this. If you're not lucky, crazy things will happen. Don't mix detach and join calls on the same thread.
https://computing.llnl.gov/tutorials/pthreads/#Joining
The value of your counter ctr depends on both the threads completing their full execution.
According to pthread_detach(3)
Once a thread has been detached, it can't be joined with
pthread_join(3) or be made joinable again.
If you remove pthread_detach call from your program, you will get the expected output.
Also, consider explicitly creating your thread joinable(or detached) for portability.

How to destroy thread in c linux

I need a thread that will call continuously in while(1), but when i use to call thread function by pthread_create() a new thread creates.
I need help on following points :~
1) Is there any method to call thread function without creating thread.
2) Is there any method to destroy the previous thread.
Sample code is
void main()
{
pthread_t thread1;
while(1)
{
pthread_create( &thread1, NULL, myFun, (void*) NULL);
}
}
void * myFun(void *ptr)
{
printf("Hello");
}
* We can not create more than 380 threads, Here we have to use only single thread.
um, I think what you really want to do is like that:
bool received_data = false;
bool beExit = false;
struct recvPacket;
pthread_mutex_t recvMutex;
void main()
{
pthread_t thread1;
void *status;
pthread_mutex_init(&recvMutex, NULL);
pthread_create(&thread1, NULL, myFun, (void*) NULL);
while(1)
{
if (received_data) {
pthread_mutex_lock(&recvMutex); // you should also synchronize received_data and beExit valuables, cuz they are shared by two threads
/* do what you want with recvPacket */
pthread_mutex_unlock(&recvMutex);
received_data == false;
}
/* do else you want, or you can let beExit = true to stop the thread */
}
if (err = pthread_join(thr_main, &status))
printf("pthread_join Error. %s\n", strerror(err)), exit(1);
}
void * myFun(void *ptr)
{
while (!beExit) {
if (true == tryRecvPacket()) {
pthread_mutex_lock(&recvMutex);
/* fill data to recvPacket */
pthread_mutex_unlock(&recvMutex);
received_data = true;
}
}
}
Suggested design is.
void * myFun(void *ptr);
volatile int thread_exit = 1;
void main()
{
pthread_t thread1;
pthread_create( &thread1, NULL, myFun, (void*) NULL);
while(1)
{
//Ask every 10 sec for killing thread like
sleep(10);
printf("Do you wish to kill [0/1]???");
scanf("%d", &thread_exit);
}
//Add code here to make main() to wait till thread dies.
//pthread_join(&thread1);
}
void * myFun(void *ptr)
{
while(thread_exit)
{
printf("Hello");
}
}
For destroying the thread, you can use pthread_kill function available
int pthread_kill(pthread_t thread, int sig);
But its not good practice to kill the thread forcefully as it might cause the problem of the memory leak.
When the parent thread is finished, then all the child threads are finished abruptly.
In your example, as child thread will be in the infinite loop so child thread never finishes. But parent thread-main thread will finish after executing the return 0 statement. So main thread will terminate the child thread also.
To overcome this situation i.e. wait until all child threads have finished, pthread_join(thread1) method is there. So the thread calling this function will wait unless thread1 has finished.
Thanks to all for quick reply..
Problem has been fixed by using following code.
setsockopt (socket_desc, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,sizeof(timeout));
Here i set the timeout for accept the tcp clients request in microseconds.. now code is working OK.

pthread_join() and sleep in main

I have a program that creates two worker threads like the following:
void *Producer(void *threadarg){
while (!terminate_producer){ //do something}
printf("Producer: finalizing thread\n");
pthread_exit(NULL);
}
void *Consumer(void *threadarg){
while (!terminate_consumer){ //do something}
printf("Consumer: finalizing thread\n");
pthread_exit(NULL);
}
// Initialize array of the worker threads
void initFuncArray(long result[])
{
result[0] = (long)&Producer;
result[1] = (long)&Consumer;
}
// The main method
int main (int argc, char* argv[]){
long th_funcs[CPUS_NUM];
initFuncArray(th_funcs);
// threads data
pthread_t tid[CPUS_NUM];
thread_data prod_th_data[CPUS_NUM];
bool pt = false;
for (int i=0;i<CPUS_NUM;i++){
prod_th_data[i].thread_id = i;
pt = pthread_create(&tid[i], NULL, (void *)th_funcs[i], (void*)&prod_th_data[i]);
if (pt) return -1;
}
sleep(5);
terminate_producer = true;
pthread_join (tid[0], NULL);
**sleep(1);**
terminate_consumer = true;
pthread_join (tid[1], NULL);
// Exiting the main thread
return 0;
}
My question is about a call to sleep before terminating the consumer thread. If I do not have this call, the program terminates normally. However, if I have that sleep, the program never terminates. I see the message that the producer thread terminates, but I do not get the message from the consumer thread. What might be the problem?
Following suggestions I modified the code as follows, however, the problem now appears even without a call to sleep in-between:
typedef void (*func_type) (void *);
pthread_mutex_t terminate_producer;
pthread_mutex_t terminate_consumer;
void *Producer(void *threadarg){
while (pthread_mutex_trylock(&terminate_producer)){ //do something}
printf("Producer: finalizing thread\n");
pthread_mutex_unlock(&terminate_producer);
return NULL;
}
void *Consumer(void *threadarg){
while (pthread_mutex_trylock(&terminate_consumer))
printf("Consumer: finalizing thread\n");
pthread_mutex_unlock(&terminate_consumer);
return NULL;
}
// Initialize array of the worker threads
void initFuncArray(func_type result[])
{
result[0] = Producer;
result[1] = Consumer;
}
// The main method
int main (int argc, char* argv[]){
func_type th_funcs[CPUS_NUM];
initFuncArray(th_funcs);
// threads data
pthread_t tid[CPUS_NUM];
thread_data prod_th_data[CPUS_NUM];
// Using mutexes as termination condition
pthread_mutex_init(&terminate_producer,NULL);
pthread_mutex_init(&terminate_consumer,NULL);
pthread_mutex_lock(&terminate_producer);
pthread_mutex_lock(&terminate_consumer);
bool pt = false;
for (int i=0;i<CPUS_NUM;i++){
prod_th_data[i].thread_id = i;
pt = pthread_create(&tid[i], NULL, (void *)th_funcs[i], (void*)&prod_th_data[i]);
if (pt) return -1;
}
sleep(5);
pthread_mutex_unlock(&terminate_producer);
pthread_join (tid[0], NULL);
pthread_mutex_unlock(&terminate_consumer);
pthread_join (tid[1], NULL);
// Exiting the main thread
return 0;
}
Flag terminate_producer represents a critical section. Producers are reading its value and main thread is rewriting it at the same time. Access to this flag should be protected with some synchronization mechanism such as mutex:
inline stopProducers() {
/* GET LOCK */
terminate_producer = 1;
/* RELEASE LOCK */
}
inline unsigned char shouldProduce() {
unsigned char terminate = 0;
/* GET LOCK */
terminate = terminate_producer;
/* RELEASE LOCK */
return !terminate;
}
void *Producer(void *threadarg){
while (shouldProduce()){ /* do something */ }
printf("Producer: finalizing thread\n");
return NULL; // <-- use return instead of pthread_exit
}
and in main you would call stopProducers(); instead of rewriting the flag;
It could be due to the compiler heuristically concluding (as an optimization) that terminate_consumer is a variable which is only read in the consumer thread, so it "caches" it in a register and never reads it.
Can you change the declarations of terminate_producer and terminate_consumer to:
volatile int terminate_producer;
volatile int terminate_consumer;
.. and try again?

How to make main thread wait for all child threads finish?

I intend to fire 2 threads in the main thread, and the main thread should wait till all the 2 child threads finish, this is how I do it.
void *routine(void *arg)
{
sleep(3);
}
int main()
{
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, NULL);
pthread_join(&tid, NULL); //This function will block main thread, right?
}
}
In the above code, pthread_join indeed makes main thread wait for the child threads, but the problem is, the second thread won't be created untill the first one finishes. This is not what I want.
What I want is, the 2 threads get created immediatly in the main thread, and then main thread waits for them to finish. Seems like pthread_join cannot do the trick, can it?
I thought, maybe via a semaphore I can do the job, but any other way?
int main()
{
pthread_t tid[2];
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, routine, NULL);
}
for (int i = 0; i < 2; i++)
pthread_join(tid[i], NULL);
return 0;
}
First create all the threads, then join all of them:
pthread_t tid[2];
/// create all threads
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, routine, NULL);
}
/// wait all threads by joining them
for (int i = 0; i < 2; i++) {
pthread_join(tid[i], NULL);
}
Alternatively, have some pthread_attr_t variable, use pthread_attr_init(3) then pthread_attr_setdetachedstate(3)
on it, then pass its address to pthread_create(3) second argument. Thos would create the threads in detached state. Or use pthread_detach as explained in Jxh's answer.
Remember to read some good Pthread tutorial. You may want to use mutexes and condition variables.
You could use frameworks wrapping them, e.g. Qt or POCO (in C++), or read a good C++ book and use C++ threads.
Conceptually, threads have each their call stack and are related to continuations. They are "heavy".
Consider some agent-oriented programming approach: as a rule of thumb, you don't want to have a lot of threads (e.g. 20 threads on a 10 core processor is reasonable, 200 threads won't be unless a lot of them are sleeping or waiting) and and do want threads to synchronize using mutex and condition variables and communicate and/or synchronize with other threads quite often (several times per second). See also poll(2), fifo(7), unix(7), sem_overview(7) with shm_overview(7) as another way of communicating between threads. In general, avoid using signal(7) with threads (read signal-safety(7)...), and use dlopen(3) with caution (probably only in the main thread).
A pragmatical approach would be to have most of your threads running some event loop (using poll(2), pselect(2), perhaps eventfd(2), signalfd(2), ....), perhaps communicating using pipe(7) or unix(7) sockets. See also socket(7).
Don't forget to document (on paper) the communication protocols between threads. For a theoretical approach, read books about π-calculus and be aware of Rice's theorem : debugging concurrent programs is difficult.
You could start the threads detached, and not worry about joining.
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, NULL);
pthread_detach(tid);
}
pthread_exit(0);
Or, alternatively, you can have the thread that dies report back to the main thread who it is, so that the threads are joined in the order they exited, rather than in the order you created them in.
void *routine(void *arg)
{
int *fds = (int *)arg;
pthread_t t = pthread_self();
usleep((rand()/(1.0 + RAND_MAX)) * 1000000);
write(fds[1], &t, sizeof(t));
}
int main()
{
int fds[2];
srand(time(0));
pipe(fds);
for (int i = 0; i < 2; i++) {
pthread_t tid;
pthread_create(&tid, NULL, routine, fds);
printf("created: %llu\n", (unsigned long long)tid);
}
for (int i = 0; i < 2; i++) {
pthread_t tid;
read(fds[0], &tid, sizeof(tid));
printf("joining: %llu\n", (unsigned long long)tid);
pthread_join(tid, 0);
}
pthread_exit(0);
}
#include<stdio.h>
#include<pthread.h>
int icnt = 0; //in non_bss data segment
pthread_mutex_t lock; //lock variable created stored into bss data segment
void *Thread_count(void* args) //syncronization
{
pthread_mutex_lock(&lock); //lock aquire
icnt++;
for(int x = 1; x <= icnt; x++)
{
printf("Hello from Thread_count : %d \n",icnt);
}
printf("\n");
pthread_mutex_unlock(&lock); //release lock
pthread_exit(NULL); //exit from child thread
}
int main()
{
pthread_t threads[4]; //created array of {unsigned long int}
int status = 0;
//creating threads in loop
for(int i = 1; i <= sizeof(threads)/sizeof(threads[0]); i++)
{
pthread_create(&threads[i], NULL, &Thread_count, NULL);
}
//waiting for threads in loop
for(int j = 1; j <= sizeof(threads)/sizeof(threads[0]); j++)
{
pthread_join(threads[j], &status);
printf("Thread number : %d <--> Thread status : %d\n",j, status);
}
pthread_exit(0); //end of main thread
}

Resources