multithread launching order - c

I have 4 threads to create thread1, thread2, thread3 and thread4:
pthread_create(thread1,NULL,thread_func1,NULL);
pthread_create(thread2,NULL,thread_func2,NULL);
pthread_create(thread3,NULL,thread_func3,NULL);
pthread_create(thread4,NULL,thread_func4,NULL);
looking in the debug , The order of launched threads is not the same as defined in the source code.
Are there a solution to launch the threads with an order that I could define?

The launch order is sequential, in that the create calls happen in the order they're written.
However the scheduler for whatever reason isn't scheduling the newly launched threads in the order you hoped. If the order matters perhaps threads isn't what you want? The big advantage with threads is that they don't always get scheduled in a sequential order!
If you really want though you can use synchronisation primitives (e.g. a series of mutexes, or a condvar) to ensure that up to a certain point happens in predictable order, but from that point onwards the order will still be down to the whims of the scheduler. As an example this code guarantees that each thread will print its ID in the order they were created:
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void sync_threads(const int num, int *cur) {
pthread_mutex_lock(&mut);
while (*cur != num) {
pthread_cond_wait(&cond, &mut);
}
// Do work that must happen in order here:
printf("Thread: %d\n", num);
++*cur;
pthread_mutex_unlock(&mut);
pthread_cond_broadcast(&cond);
}
static int num = 1;
void *thread1(void *d) {
sync_threads(1,&num);
while (1); // Rest of work happens whenever
return NULL;
}
void *thread2(void *d) {
sync_threads(2,&num);
while (1);
return NULL;
}
void *thread3(void *d) {
sync_threads(3,&num);
while (1);
return NULL;
}
void *thread4(void *d) {
sync_threads(4,&num);
while (1);
return NULL;
}
int main() {
pthread_t t1,t2,t3,t4;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_create(&t3, NULL, thread3, NULL);
pthread_create(&t4, NULL, thread4, NULL);
while(1) {
// some work
}
}
I've used while(1); to simulate some real work happening. It does this with a mutex protecting the "current" thread, i.e. the order of initialisation and then a condvar to make sleeping/waking possible. It broadcasts to all threads who then check to see which one is up next. You could design as system that skips the broadcast, but that complicates things for relatively little gain.
You can also add more synchronisation if required at other points, but the more you synchronise things the less point there is in having threads in the first place.
Ideally if things need to happen in a predictable order they should be done before spawning threads, not as soon as the threads spawn, e.g.:
fixed_init_for_thread1();
fixed_init_for_thread2();
fixed_init_for_thread3();
fixed_init_for_thread4();
pthread_create(thread1,NULL,thread_func1,NULL);
pthread_create(thread2,NULL,thread_func2,NULL);
pthread_create(thread3,NULL,thread_func3,NULL);
pthread_create(thread4,NULL,thread_func4,NULL);
such that by the time the threads are created you don't care which one actually gets given the chance to run first.

I don't think you really care which thread executed first. If you just need an unique identifier for the four threads, check pthread_self. To have sequential IDs, call the ID allocator from within the thread; or generate the ID and pass it as user parameter when calling pthread_create.

here after the solution I used
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static bool wait = TRUE;
void thread_sync() {
pthread_mutex_lock(&mut);
wait = FALSE;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
void thread_wait_sync() {
pthread_mutex_lock(&mut);
if (wait==TRUE)
{
pthread_cond_wait(&cond,&mut);
}
wait = TRUE;
pthread_mutex_unlock(&mut);
}
void *thread1(void *d) {
thread_sync();
while (1); // Rest of work happens whenever
return NULL;
}
void *thread2(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread3(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread4(void *d) {
while (1);
return NULL;
}
int main() {
pthread_t t1,t2,t3,t4;
pthread_create(&t1, NULL, thread1, NULL);
thread_wait_sync();
pthread_create(&t2, NULL, thread2, NULL);
thread_wait_sync();
pthread_create(&t3, NULL, thread3, NULL);
thread_wait_sync();
pthread_create(&t4, NULL, thread4, NULL);
while(1) {
// some work
}
}

Move 'pthread_create(thread2,NULL,thread_func2,NULL);' into thread_func1()
Move 'pthread_create(thread3,NULL,thread_func2,NULL);' into thread_func2()
Move 'pthread_create(thread4,NULL,thread_func2,NULL);' into thread_func3()
This is VERY close to the other question posted recently and just as err.. 'strange'

Related

Thread synchronisation using semaphore for c

I am writing a c program to create three threads(1,2,3) such that at any given point of time only one thread must execute and print the output on console in the order 123123123123.........
I am making use of semaphore for synchronization.
I am having an issue with the code i have written. the code doesn't print it in the order 123123... the order is random and stops after a while.
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#include<assert.h>
#include<stdlib.h>
sem_t sem_1;
void *func1(void *arg){
int err1=0;
while(1){
err1=sem_wait(&sem_1);
assert(err1==0);
printf("thread 1\n");
}
//return NULL;
}
void *func2(void *arg){
int err2=0;
while(1){
err2=sem_wait(&sem_1);
assert(err2==0);
printf("thread 2\n");
}
// return NULL;
}
void *func3(void *arg){
int err3=0;
while(1){
err3=sem_wait(&sem_1);
assert(err3==0);
printf("thread 3\n");
}
// return NULL;
}
int main(){
pthread_t *t1,*t2,*t3;
int i=0,rc=0,c1=0,c2=0,c3=0;
t1=(pthread_t *)malloc(sizeof(*t1));
t2=(pthread_t *)malloc(sizeof(*t2));
t3=(pthread_t *)malloc(sizeof(*t3));
i=sem_init(&sem_1,0,1);
assert(i==0);
c1=pthread_create(t1,NULL,func1,NULL);
assert(c1==0);
c2=pthread_create(t2,NULL,func2,NULL);
assert(c2==0);
c3=pthread_create(t3,NULL,func3,NULL);
assert(c3==0);
while(1){
rc=sem_post(&sem_1);
assert(rc==0);
sleep(1);
}
return 0;
}
Why would you even expect them in in an order?
Your threads do things inbetween the different waits, and according to the system scheduler, these can take different amount of time.
printf is a buffered operation that gives you exclusive access to a shared resource. So in addition to your semaphore there is a hidden lock somewhere, that also regulates the progress of your threads. Don't expect the prints to appear in order, even if the calls themselves are.
Then, for the end, using assert here is really a very bad idea. All sem_t operations can (and will) fail spuriously, so it is really bad to abort, just because such a failure.
In fact, sem_t is really a low level tool, and you should never use it without checking return values and without having a fall back strategy if such a call fails.
Of course. I can't see any order related synchronization mechanism.
One of the options to achieve the strict order is to have one semaphore per thread:
sem_t sem[3];
// ...
while(1) {
for(n = 0; n < 3; n++) {
rc=sem_post(&sem[n]);
assert(rc==0);
}
sleep(1);
}
Below Code will help to solve the problem, one semaphore for each thread used to achieve synchronization. The initial value of the semaphore does the job. used usleep to launch thread in sequence manner for needed output. The same can be done by using Mutex lock and cond variables
//declaring semaphore
sem_t sema1;
sem_t sema2;
sem_t sema3;
void* t1(void *arg)
{
for(int j=0;j<10;j++)
{
sem_wait(&sema1);
printf("Thread 1 \n");
sem_post(&sema2);
}
printf("T1 return\n");
return NULL;
}
void* t2(void *arg)
{
for(int j=0;j<10;j++)
{
sem_wait(&sema2);
printf("Thread 2 \n");
sem_post(&sema3);
}
printf("T2 return\n");
return NULL;
}
void* t3(void *arg)
{
for(int j=0;j<10;j++)
{
sem_wait(&sema3);
printf("Thread 3 \n");
sem_post(&sema1);
}
printf("T3 return \n");
return NULL;
}
int main()
{
pthread_t tid1, tid2,tid3;
sem_init(&sema1,0,1);
sem_init(&sema2,0,0);
sem_init(&sema3,0,0);
pthread_create(&tid1, NULL, t1, NULL);
usleep(100);
pthread_create(&tid2, NULL, t2, NULL);
usleep(100);
pthread_create(&tid3, NULL, t3, NULL);
pthread_join(tid3, NULL);
pthread_join(tid2, NULL);
pthread_join(tid1, NULL);
sem_destroy(&sema1);
sem_destroy(&sema2);
sem_destroy(&sema3);
return 0;
}

Ordering the execution of two threads

I wanna write two threads, first will read a string from the console, and the second will output the number of characters in it.
To do so, I have to set the order of executing the threads, reading first, writing second.
Also I want one thread to execute at the time.
How can I do this?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *printCharacterNumber(void *ptr);
void *readMessage(void *ptr);
int main()
{
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create(&thread1, NULL, printMessage, NULL);
iret2 = pthread_create(&thread2, NULL, printCharacterNumber, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
void *readMessage(void *ptr)
{
char *message;
fscan("%s", &message);
}
void *printCharacterNumber(void *ptr)
{
printf("%s", message); // I'll add counting when it will work
}
The biggest interest of genine (pthread) threads is to enable parallel execution (taking profit of the several cores most laptops and desktops have)...
Read some pthread tutorial ...
You may want to use barriers. Read more about pthread_barrier_wait & pthread_barrier_init
If you want to serialize some counter, you could use (with recent C11 compilers, e.g. GCC 4.9) some atomic builtins, or more usually a mutex, see pthread_mutex_init & pthread_mutex_lock etc....:
static pthread_mutex_t mtx = PTHREAD_MUTEX_INIT;
static long counter;
void increment_serialized_counter (void) {
pthread_mutex_lock(&mtx);
counter++;
pthread_mutex_unclock(&mtx);
}
long get_serialized_counter (void) {
long r = 0;
pthread_mutex_lock(&mtx);
r = counter;
pthread_mutex_unclock(&mtx);
return r;
}
You probably should use a mutex for your message variable, if it was static!

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.

multithreading(pthread) compete code

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
int global;
int i = 30;
int j = 30;
int k = 30;
pthread_mutex_t mutex;
void* child1(void* arg)
{
while(k--)
{
pthread_mutex_lock(&mutex);
global++;
printf("from child1\n");
printf("%d\n",global);
pthread_mutex_unlock(&mutex);
}
}
void* child2(void* arg)
{
while(j--)
{
pthread_mutex_lock(&mutex);
global++;
printf("from child1\n");
printf("%d\n",global);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid1, NULL, child1, NULL);
pthread_create(&tid2, NULL, child2, NULL);
while(i--)
{
pthread_mutex_lock(&mutex);
global++;
printf("from main\n");
printf("%d\n",global);
pthread_mutex_unlock(&mutex);
}
return 0;
}
I'm new to pthread and multithreading, the result of this code is from main xx and child1 appeared rarely, the three threads never appear together, what's the problem?
Most of time in the critical sections will be spent in the printf calls. You might try:
{
int local;
pthread_mutex_lock(& mutex);
local = ++global;
pthread_mutex_unlock(& mutex);
printf("from <fn>\n%d\n", local);
}
This still doesn't give any guarantee of 'fairness' however, but the printf call is very likely to use a system call or I/O event that will cause the scheduler to kick in.
Your program is similar to the Dining Philosophers Problem in many respects. You don't want any thread to 'starve', but you have contention between threads for the global counter, and you want to enforce an orderly execution.
One suggestion in code replace printf("from child1\n"); to printf("from child2\n"); in void* child2(void* arg) function. And if you want ensure all threads to complete please add the following lines at end of main function.
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
I think you should use 3 differents mutex , by the way use pconditional control in order to avoid having unsafe access

multi thread launch arrangement

I have 2 thread to create thread1 and thread2. When creating threads with:
pthread_create(&thread1, NULL, &function_th1, NULL);
pthread_create(&thread2, NULL, &function_th2, NULL);
The thread2 is launched before the thread1 and I'm looking for a solution to start thread1 before thread2.
Not looking for this solution:
pthread_create(&thread2, NULL, &function_th2, NULL);
pthread_create(&thread1, NULL, &function_th1, NULL);
There is no relation between when a thread creation call is issued and when the thread actually starts executing. It all depends on implementation, OS, etc. that's why you are seeing the two threads actually starting in a seemingly random order.
If you need thread 1 to start before thread 2 you probably have some data/logical dependency on some event. In this case you should use a condition variable to tell thread 2 when to actually begin executing.
// condition variable
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// associated mutex
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// state for condition variable
int shouldWait = 1;
...
void* function_th1(void* p) {
// execute something
// signal thread 2 to proceed
pthread_mutex_lock(&mutex);
shouldWait = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
// other stuff
}
void* function_th2(void* p) {
// wait for signal from thread 1
pthread_mutex_lock(&mutex);
while(shouldWait) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
// other stuff
}
Move the 'pthread_create(&thread2, NULL, &function_th2, NULL);' to the top of the 'function_th1' function.
That will certainly achieve what you ask for, no complex signalling required.
Whether what you ask for is what you actually want or need is another matter.
here after the solution I suggest
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static bool wait = TRUE;
void thread_sync() {
pthread_mutex_lock(&mut);
wait = FALSE;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
void thread_wait_sync() {
pthread_mutex_lock(&mut);
if (wait==TRUE)
{
pthread_cond_wait(&cond,&mut);
}
wait = TRUE;
pthread_mutex_unlock(&mut);
}
void *thread1(void *d) {
thread_sync();
while (1); // Rest of work happens whenever
return NULL;
}
void *thread2(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread3(void *d) {
thread_sync();
while (1);
return NULL;
}
void *thread4(void *d) {
while (1);
return NULL;
}
int main() {
pthread_t t1,t2,t3,t4;
pthread_create(&t1, NULL, thread1, NULL);
thread_wait_sync();
pthread_create(&t2, NULL, thread2, NULL);
thread_wait_sync();
pthread_create(&t3, NULL, thread3, NULL);
thread_wait_sync();
pthread_create(&t4, NULL, thread4, NULL);
while(1) {
// some work
}
}

Resources