Products > Programming
Linux:: how to synchronize the main with a thread in C
0db:
hi guys
I am still studying Multithreading in C. I know how to synchronize two or more threads via Mutex and Conditions, but I don't know how to stop a thread until the main program has reached certain conditions.
Is there any full guide with examples?
SiliconWizard:
Use semaphores.
You can then wait on a semaphore in a thread, and post it in another thread (including the main thread) to wake the thread up again and exit the wait.
PlainName:
--- Quote ---Is there any full guide with examples?
--- End quote ---
What OS are you using or thinking about? If it's FreeRTOS you should download the 'hands-on tutorial'.
Chapter 6.4 describes interrupt synchronization which should cover what you want to know. The pukka FreeRTOS API guide details the functions with examples, but this tutorial covers why you might want to use them.
Edit: just noticed this is the Linux topic. Duh! But the principle remains the same whatever you're using.
0db:
--- Quote from: SiliconWizard on March 30, 2020, 06:36:24 pm ---Use semaphores.
You can then wait on a semaphore in a thread, and post it in another thread (including the main thread) to wake the thread up again and exit the wait.
--- End quote ---
You write "main thread", but in my case, I am in the int main() { ... } body of a C program and I need to wait until a thread, which will never terminate, reaches a particular state.
Can I sill use semaphores, mutes, condition variables, &C in this case?
0db:
--- Code: ---// C program to demonstrate working of Semaphores
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg)
{
//wait
sem_wait(&mutex);
printf("\nEntered..\n");
//critical section
sleep(4);
//signal
printf("\nJust Exiting...\n");
sem_post(&mutex);
}
int main()
{
sem_init(&mutex, 0, 1);
pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL);
sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
return 0;
}
--- End code ---
basically, I have 16 threads, and their synchronization looks like the above code. However, in main() {} I have this line
--- Code: ---int main()
{...
/*
* wait untill tip has completed its process
*/
wait_for_tip_completed(tip);
--- End code ---
wait_for_tip_completed is an active waiting loop
--- Code: ---void wait_for_tip_completed( ....
while (1)
{
if (tip.completed) return;
}
--- End code ---
This somehow works, but ... it doesn't look the right way.
Navigation
[0] Message Index
[#] Next page
Go to full version