I have written a sample program to implement array of threads.There are two thread functions. Is there any way to define a fixed value of time (in seconds) after which all the threads will automatically stop?
Sample program:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void * threadFunc1(void * arg)
{
int id = *((int *) arg);
printf("Inside threadfunc2 for thread %d\n",id)
while(1);
}
void * threadFunc2(void * arg)
{
int i= *((int *)arg);
printf("Inside threadfunc2 for thread %d\n",i)
while(1);
}
int main(void)
{
pthread_t thread[10];
for(int i=0;i<10;i++)
{
pthread_create(&thread[i],NULL,threadFunc1,(void*)&i );
pthread_create(&thread[i],NULL,threadFunc,(void*)&i );
}
for (i=0;i<total;i++)
{
pthread_join(thread[i],NULL);
}
return 0;
}
Instead of waiting for the threads with pthread_join you could put your main thread to sleep, e.g with nanosleep. If you then quit your main without joining, your whole process will be killed.
No, there is not. Threads do not 'automatically stop'
Related
I have new data appearing over a bus. I want my main thread to "wake up" when the new data arrives. My original version of the code is this:
#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
int data = 0;
void* thread_func(void* args)
{
while(1)
{
sleep(2);
data = random() % 5;
}
return NULL;
}
int main()
{
int tid;
pthread_create(&tid, NULL, &thread_func, NULL);
while(1)
{
// Check data.
printf("New data arrived: %d.\n", data);
sleep(2);
}
return 0;
}
But clearly an infinite while loop in the main thread is overkill. So I thought how about this?
#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
int data = 0;
pthread_mutex_t mtx;
void* thread_func(void* args)
{
while(1)
{
sleep(2);
// Data has appeared and can be read by main().
data = random() % 5;
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
int tid;
pthread_mutex_init(&mtx, NULL);
pthread_create(&tid, NULL, &thread_func, NULL);
while(1)
{
pthread_mutex_lock(&mtx);
printf("New data has arrived: %d.\n", data);
}
return 0;
}
This works, but is it the best way?
In actual fact, I don't just have a main thread, but several threads that I would like to be asleep until new data for them arrived. This would involve using one mutex lock for each thread. Is this the best way to do things?
I hope it's clear. Thanks.
You can use pthread_cond_wait to wait for a change on the data you share between your threads. This function automatically blocks your mutex and you have to release it afterwards. To notify your threads that the data is ready use the pthread_cond_signal function.
But be careful, you must always lock and unlock your mutex in each of your threads, not as you do in your example.
I am using a translator because I am not good at English.
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
pthread_rwlock_t R_Lock;
int ac=0;
void* RD_LOCK(void* arg) {
pthread_rwlock_rdlock(&R_Lock);
printf("%d\n",ac); // ac is global variable 0
sleep(1);
pthread_rwlock_unlock(&R_Lock);
}
void* WR_LOCK(void* arg) {
pthread_rwlock_wrlock(&R_Lock);
printf("RW LCOK\n");
ac++;
printf("%d\n",ac);
sleep(1);
pthread_rwlock_unlock(&R_Lock);
}
void DO_RW_LCOK(){
pthread_t RW[3];
pthread_rwlock_init(&R_Lock, NULL);
pthread_create(&RW[0], NULL, RD_LOCK,NULL); //==0 thread
pthread_create(&RW[1], NULL, RD_LOCK,NULL); //==1 thread
pthread_create(&RW[2], NULL, WR_LOCK,NULL); //==2 thread
pthread_rwlock_destroy(&R_Lock);
for(int i=0; i<3;i++)
pthread_join(RW[i],NULL);
}
int main(){
DO_RW_LCOK();
return 0;
}
void* RD_LOCK(void* arg) {
pthread_rwlock_rdlock(&R_Lock);
printf("%d\n",ac); // ac is global variable 0
sleep(1);
pthread_rwlock_unlock(&R_Lock); }
void* WR_LOCK(void* arg) {
pthread_rwlock_wrlock(&R_Lock);
ac++;
printf("%d\n",ac);
sleep(1);
pthread_rwlock_unlock(&R_Lock);
}
int main(){
DO_RW_LOCK();
return 0;
}
I tried to execute 3 threads.
0,1 thread used readlock and 2 thread used writelcok.
My prediction after the program runs After the 0,1 thread, 2 thread was executed.
However, the run order is 2thread,0thread,1thread
I don't understand this.
Threads are always unpredictable. So the order may really change and be unexpected.
In order to guarantee that your threads will be in the order that you want them to be, add a wait option which will make the thread wait if the other threads are not done. Just use wait and notify.
I did not get which thread type you are using but here is a pseudocode.
Lock waitAndNotify;
int rdDone = 0;
void* RD_LOCK(void* arg) {
pthread_rwlock_rdlock(&R_Lock);
rdDone++;
notify(waitAndNotify);
printf("%d\n",ac); // ac is global variable 0
sleep(1);
pthread_rwlock_unlock(&R_Lock); }
void* WR_LOCK(void* arg) {
pthread_rwlock_wrlock(&R_Lock);
if(rdDone!=2)
wait(waitAndNotify);
ac++;
printf("%d\n",ac);
sleep(1);
pthread_rwlock_unlock(&R_Lock);
}
Now this is just a little test, and part of a school assignment. In my code printf is not printing at least to me being able to see it. Is this a result of the thread not functioning? The print line works outside of the thread. Thank you for any help.
I am new to threading in c.
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer,argv[i]);
i++;
}
In your code, the parent thread of execution that created another thread finishes execution without waiting for its child threads to finish. And threads, unlike processes, once the parent thread terminates, all its child threads of execution terminate as well.
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer, argv[i]);
i++;
pthread_join(thread, NULL);
}
}
Doing this will allow the thread created to run, until it finishes execution. The pthread_join will wait for the thread to complete its execution and then move ahead.
EDIT
As people did mention in the comments, it is probably worthless trying to spawn a single thread and joining it immediately, making it no better than a single thread of execution. Hence, for the sake of experimentation, the code can be modified as follows:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
}
int main(int argc, char* argv[]){
int i = 1;
pthread_t thread[argc - 1];
while(i < argc)
{
pthread_create(&thread[i-1], NULL, threadServer, argv[i]);
i++;
}
for (i = 0; i < argc - 1; ++i)
{
pthread_join(thread[i], NULL);
}
}
I am practicing multi-threading.
I create two posix threads that display a text to the screen (infinite loop), but it seem only the first thread run. I modify the program without looping, first thread prints, following is second thread. It seems that my thread are not parallel, first thread has to finish before thread two start.
How can I make them parallel?
Thanks,
hdr.h
#ifndef HDR_HDR_H_
#define HDR_HDR_H_
#define HDR_HDR_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#endif /* HDR_HDR_H_ */
multithread01.c
#include "../hdr/myfunc.h"
pthread_mutex_t lock;
int main(int argc, char **argv)
{
pthread_t tid01;
pthread_t tid02;
void * status01;
void * status02;
pthread_create(&tid01, NULL, PrintOut01(), NULL);
pthread_create(&tid02, NULL, PrintOut02(), NULL);
pthread_join(&tid01, &status01);
pthread_join(&tid02, &status02);
return 0;
}
myfunc.h
#ifndef HDR_MYFUNC_H_
#define HDR_MYFUNC_H_
#include "../hdr/hdr.h"
void * PrintOut01 (void);
void * PrintOut02 (void);
#endif /* HDR_MYFUNC_H_ */
myfunc.c
#include "../hdr/hdr.h"
extern pthread_mutex_t lock;
void * PrintOut01 ()
{
while (1)
{
pthread_mutex_lock(&lock);
printf ("This is thread 01\n");
pthread_mutex_unlock(&lock);
}
}
void * PrintOut02 ()
{
while (1)
{
pthread_mutex_lock(&lock);
printf ("This is thread 02\n");
pthread_mutex_unlock(&lock);
}
}
It's because you are calling the functions in your pthread_create call, you're not passing the function pointers.
Compare the incorrect
pthread_create(&tid01, NULL, PrintOut01(), NULL);
with the correct
pthread_create(&tid01, NULL, PrintOut01, NULL);
If you remove the loops in the functions, and create the threads like you do in the code in the question, then the pthread_create will use whatever you return from the functions as the pointer to the thread function, and unless you return a pointer to a function you will have undefined behavior.
I am learning to use semaphores and below is a small scenario which I've tried to implement. Its behaving weird in a way. After sem_wait() gets unblocked first time, its not getting blocked again and keeps on looping, not getting why. Is this the right way or right scenario to use semaphore?
EDIT: I just realized that if I uncomment the sleep after sem_post, it works fine. .Reason being it was repeatedly doing sem_post() before thread could do coin=0 I believe. But is it right to use sleep this way with semaphores. I believe this would be considered a bad practice?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#define MAX_MSG_LEN 256
sem_t sem1;
sem_t sem2;
int coin=0;
void *thrdFun1(void *arg);
void *thrdFun2(void *arg);
void toggleCase(char *buf, int cnt);
int main()
{
pthread_t thrd1;
char argmsg1[] = "Thread1: Waiting to deliver\n";
int thNum;
int res;
res = sem_init(&sem1, 0,0);
// res = sem_init(&sem2, 0,0);
res = pthread_create(&thrd1, NULL, thrdFun1, argmsg1);
while(1)
{
if (coin==0)
{
printf("no coin: please enter coin\n");
scanf("%d",&coin);
}
else
{
sem_post(&sem1);
// sleep(1);
}
}
return 0;
}
void *thrdFun1(void *arg)
{
while(1)
{
printf("I'm %s\n",(char *)arg);
sem_wait(&sem1);
printf("Delivered...\n");
coin=0;
sleep(1);
}
}
Semaphores are used to control Critical-Section Access. In this case, critical section would be the output shell. The thread may or may not start promptly when the pthread_create() is called. Also, sem_wait() will decrease the value of sem1 with each call. Thus, when you include sleep(1) in the thrdFun1 function, there may be undefined behaviour :)
You need to remove sleep(1); from function thrdFun1. After this there will not be any need of sleep(1) in main.
You realized it right, it is repeatedly doing sem_post() before thread could do coin=0 when removing all sleeps.
To solve this you could use second semaphore (you already tried it seems) like below,
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#define MAX_MSG_LEN 256
sem_t sem1;
sem_t sem2;
int coin=0;
void *thrdFun1(void *arg);
void *thrdFun2(void *arg);
void toggleCase(char *buf, int cnt);
int main()
{
pthread_t thrd1;
char argmsg1[] = "Thread1: Waiting to deliver\n";
int thNum;
int res;
res = sem_init(&sem1, 0,0);
res = sem_init(&sem2, 0,0);
res = pthread_create(&thrd1, NULL, thrdFun1, argmsg1);
while(1)
{
if (coin==0)
{
printf("no coin: please enter coin\n");
scanf("%d",&coin);
}
else
{
sem_post(&sem1); // Coin is spun
sem_wait(&sem2); // Wait till it is caught
}
}
return 0;
}
void *thrdFun1(void *arg)
{
while(1)
{
printf("I'm %s\n",(char *)arg);
sem_wait(&sem1); // Wait to spin the coin
coin=0;
sem_post(&sem2); // inform as caught
printf("Delivered...\n");
}
}
there is a chance that "Thread1: Waiting to deliver" this string can get printed many times.
What you are trying to achieve is looks like producer-consumer problem.
You required two semaphore to achive this.
main function:
while(1)
{
if (coin==0)
{
printf("no coin: please enter coin\n");
scanf("%d",&coin);
}
else
{
sem_post(&sem1);
sem_wait(&sem2)
}
}
in thread function
while(1)
{
printf("I'm %s\n",(char *)arg);
sem_wait(&sem1);
printf("Delivered...\n");
coin=0;
sem_post(&sem2)
}