Sem_wait() not blocking after first true condition - c

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)
}

Related

How do I notify a thread that new data is available using pthreads?

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.

Mutex Deadlock (pthread_mutex)

I can't understand why in this code I get a deadlock.
I have defined this mutexes:
mutex3: = 0 (LOCKED)
mutex2: = 1 (UNLOCKED)
I have 2 processes: Father and son. Each has N threads that I pass by argument. The child's threads contend with the father's threads a "resource" (typical producer / consumer problem).
Thanks in advance!
I suppose the problem is here:
void * func_padre(void * n)
{
while(1)
{
pthread_mutex_lock(&mutex2);
printf("Scrivi messaggio: ");
fflush(stdout);
scanf("%[^\n]",(char *)addr_mem);
getchar();
pthread_mutex_unlock(&mutex3);
}
}
void * func_figlio(void * n)
{
while(1)
{
pthread_mutex_lock(&mutex3);
write(fd,addr_mem,4096);
lseek(fd,0,SEEK_SET);
memset(addr_mem,0,4096);
pthread_mutex_unlock(&mutex2);
}
}
CODE:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
void * addr_mem;
pthread_mutex_t mutex2,mutex3;
int fd;
void * func_padre(void * n)
{
while(1)
{
pthread_mutex_lock(&mutex2);
printf("Scrivi messaggio: ");
fflush(stdout);
scanf("%[^\n]",(char *)addr_mem);
getchar();
pthread_mutex_unlock(&mutex3);
}
}
void * func_figlio(void * n)
{
while(1)
{
pthread_mutex_lock(&mutex3);
write(fd,addr_mem,4096);
lseek(fd,0,SEEK_SET);
memset(addr_mem,0,4096);
pthread_mutex_unlock(&mutex2);
}
}
int main(int argc, char*argv[])
{
if(argc<2)
{
printf("POCHI PARAMETRI\n");
fflush(stdout);
exit(-1);
}
int val=strtol(argv[2],0,10);
fd = open(argv[1],O_CREAT|O_RDWR,0666);
lseek(fd,0,SEEK_SET);//USELESS
///SHARED MEMORY
int id_mem;
id_mem = shmget(6543,4096,IPC_CREAT|0666);
addr_mem = shmat(id_mem,NULL,0);
/////////////////////
/// MUTEX
pthread_mutex_init(&mutex2,NULL);
pthread_mutex_init(&mutex3,NULL);
pthread_mutex_lock(&mutex3);
/////////////////////
pthread_t tid;
int i=0;
int pid;
pid = fork();
if(pid==0)
{
//CHILD
for(i=0; i<val; i++)
pthread_create(&tid,NULL,func_figlio,NULL);
while(1)
{
pthread_mutex_lock(&mutex3);
write(fd,addr_mem,4096);
memset(addr_mem,0,4096);
pthread_mutex_unlock(&mutex2);
}
}
else
{
//FATHER
for(i=0; i<val; i++)
pthread_create(&tid,NULL,func_padre,NULL);
while(1)
{
pthread_mutex_lock(&mutex2);
printf("Scrivi messaggio: ");
fflush(stdout);
scanf("%[^\n]",(char *)addr_mem);
getchar();
pthread_mutex_unlock(&mutex3);
}
}
}
Your problem is not a deadlock, it's just buggy code. A thread cannot unlock a mutex it did not lock. Your while loops all unlock mutexes they do not hold and never unlock the mutexes they do hold.
suggest:
have global variable that is cycled through a limited set of values, say: 0, 1, 0 ...
Use the mutex to stop other threads from progressing, I.E.
When a call (in thread) returns from locking the mutex,
then check
if the value in the global variable is for 'this' thread.
then
process the thread activities,
increment the global variable,
endif
endif
unlock the mutex
call nanosleep() to delay for a while to allow other threads to run

signal handler in child thread

I tried to install SIGINT handler for the child thread in the code below. I expect the child thread to print hello when it receives SIGINT from the parent process. However, nothing comes out and the program exits immediately.
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
typedef struct proxy_node_t{
pthread_t sub_thread;
pthread_t p_self;
}proxy_node;
proxy_node* proxy;
static void proxy_singnal_handler(){
printf("Hello\n");
return;
}
static void* t_consensus(void *arg){
signal(SIGINT,proxy_singnal_handler);
sleep(1);
return NULL;
}
int main(int argc, char **argv)
{
proxy = (proxy_node*)malloc(sizeof(proxy_node));
proxy->p_self = pthread_self();
pthread_create(&proxy->sub_thread,NULL,t_consensus,NULL);
pthread_kill(proxy->sub_thread,SIGINT);
sleep(1);
return 0;
}
There are several problems.
1) The signal handler signature is not correct. It should take an int whereas you define it with no parameter.
i.e.
static void proxy_singnal_handler(){
should be
static void proxy_singnal_handler(int sig){
2) You can't call functions that are not async-signal-safe from a signal handler (printf() in your case). See signal(7) for details. You can instead use write(2) to print that message:
printf("Hello\n");
can be:
write(1, "Hello\n", 6);
3) When main thread sends SIGINT, the t_consensus thread might not have even started. So, signal() may not have been installed yet. So, you need to make sure signal() is installed before pthread_kill() could send SIGINT.
Just to demonstrate it, I have added some sleep calls (see comments in the code). But please note that sleep() is not a good way to synchronization and if you intend to adapt this example then you should use a conditional variable instead.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
typedef struct proxy_node_t{
pthread_t sub_thread;
pthread_t p_self;
}proxy_node;
proxy_node* proxy;
static void proxy_singnal_handler(int sig){
write(1, "Hello\n", 6);
return;
}
static void* t_consensus(void *arg){
signal(SIGINT,proxy_singnal_handler);
while(1); /* infinite loop */
return NULL;
}
int main(int argc, char **argv)
{
proxy = (proxy_node*)malloc(sizeof(proxy_node));
proxy->p_self = pthread_self();
pthread_create(&proxy->sub_thread,NULL,t_consensus,NULL);
sleep(2); /* delay to ensure signal handler is installed */
pthread_kill(proxy->sub_thread,SIGINT);
sleep(2); /* delay to ensure signal gets executed before the process exits */
return 0;
}
Since #Maxim Egorushkin wanted to see a solution that exits gracefully and uses semaphores:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <semaphore.h>
typedef struct proxy_node_t{
pthread_t sub_thread;
pthread_t p_self;
}proxy_node;
proxy_node* proxy;
static void proxy_singnal_handler(int sig)
{
write(1, "Hello\n", 6);
return;
}
sem_t sema1;
sem_t sema2;
static void* t_consensus(void *arg)
{
signal(SIGINT,proxy_singnal_handler);
sem_post(&sema1); /*notify main thread that signal-handler is installed*/
sem_wait(&sema2); /*ensure thread exists to be pthread_kill'ed, could use sigsuspend instead*/
return NULL;
}
int main(int argc, char **argv)
{
sem_init(&sema1, 0, 0);
sem_init(&sema2, 0, 0);
proxy = (proxy_node*)malloc(sizeof(proxy_node));
proxy->p_self = pthread_self();
pthread_create(&proxy->sub_thread,NULL,t_consensus,NULL);
sem_wait(&sema1); /*wait until the thread has installed the signal handler*/
pthread_kill(proxy->sub_thread,SIGINT);
sem_post(&sema2); /*not strictly necessary if the thread uses sigsuspend*/
pthread_join(proxy->sub_thread, NULL);
free(proxy); /*not strictly necessary before exiting*/
sem_destroy(&sema1);
sem_destroy(&sema2);
return 0;
}

creating time specific threads

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'

Multithreaded semaphore program

I've spent quite a few hours on trying to figure this one out and I'm completly stuck. The program is supposed to start 6 threads. Where some threads start where others end. Right now, I'm trying to get one single thread (thread 0) to execute. The caps lock commenting shows where I have added code and done my mistakes. My main struggle here is dealing with the pointers. Could anyone give me any pointers (ha..ha.. :c )?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define SHARED 1
sem_t sem[6];
struct threadargs
{
int id; /* thread number */
int sec; /* how many sec to sleep */
int signal[6]; /* which threads to signal when done */
};
void *tfunc(void *arg)
{
int i;
struct threadargs *targs=arg;
sem_wait(sem); //WAIT FOR OWN SEMAPHORE
printf("Thread %d is running\n", targs->id);
sleep(targs->sec);
printf("Thread %d is completed and may wake others..\n", targs->id);
for(i=0; i<6; i++) //ITERATE OVER signal_ARRAY &
{ //WAKE THREAD NUMBER i IF
if(targs->signal[i] == 1) //signal[i] IS 1
pthread_cond_signal(&sem[i]);
}
}
int main(void)
{
int i, j;
struct threadargs *targs[6];
pthread_t tid[6];
for(i=0; i<6; i++)
{
targs[i] = (struct threadargs*) malloc(sizeof(struct threadargs));
for(j=0; j<6; j++)
{ targs[i]->signal[j]=0; }
}
targs[0]->id=1;
targs[0]->sec=1;
targs[0]->signal[1]=1;
targs[0]->signal[4]=1;
sem[0] = 0; //INITIALIZE THREAD'S SEMAPHORE TO 0 or 1
pthread_create(targs[0], NULL, tfunc, NULL) // START THREAD
for(i=0; i<6; i++)
pthread_join(tid[i], NULL);
return 0;
}
Alright. First things first, I do recommend taking a second look at your coding style. It is of course highly subjective and I won't say yours is bad, but it took me a while to figure it out (if you really want to know, I recommend the Linux coding style for C/C++ code).
Lets get on with your problem. As far as I can see, the main issue seems that you're basically comparing pointers to apples with pointers to banana's (in other words, you're using the wrong pointer type in the wrong place).
To make sure that calls to functions and the like are correct, make sure to look up the API documentation for functions that are new to you (examples: pthread_create, sem_init, sem_wait, sem_post, pthread_cond_signal).
As you can see, pthread_cond_signal doesn't take a sem_t* as argument, and therefore you can't pass one to it and expect it to work. Below you'll find an example program showing how semaphores are used.
First, a new thread is created which will be put in waiting state instantly. As soon as the main tread finished counting from 0 to 150, it will post ('unlock') the semaphore and allowing the second thread to finish its execution.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
static sem_t sem_thread_one;
static pthread_t thread_one_data;
static int x;
static void *tfunc(void *arg)
{
sem_wait(&sem_thread_one);
printf("Thread 1 is running. The value of x is %i\n", x);
return NULL;
}
int main(int argc, char **argv)
{
sem_init(&sem_thread_one, 0 /* don't share between processes */, 0);
if(pthread_create(&thread_one_data, NULL, &tfunc, NULL)) {
fprintf(stderr, "Could not create thread, exiting!\n");
return -EXIT_FAILURE;
}
while(x < 150) {
x++;
}
sem_post(&sem_thread_one);
if(pthread_join(thread_one_data, NULL)) {
fprintf(stderr, "Could not join threads, exiting!\n");
return -EXIT_FAILURE;
}
sem_destroy(&sem_thread_one);
printf("Program ran succesfully!\n");
return -EXIT_SUCCESS;
}
Save in a file sem.c and compile & link using:
gcc -Wall -Os -pthread -o sem_test sem.c
Now a second example, but now using pthread_cond_t. The functionality of the program is somewhat similar, it waits for a counter to reach a certain number.
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
static pthread_t thread_one_data, thread_two_data;
static volatile int x, y, idx = 10;
static int count = 1;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
static void *cond_test_wait(void *arg)
{
pthread_mutex_lock(&mutex);
while(count < 10) {
printf("Waiting for `count < 10' to become true\n");
pthread_cond_wait(&condition, &mutex);
}
pthread_mutex_unlock(&mutex);
printf("Test wait thread finished. Value of count: %i\n", count);
return NULL;
}
static void *cond_test_signal(void *arg)
{
while(count < 10) {
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condition);
/* do more intelligent things here */
count++;
pthread_mutex_unlock(&mutex);
}
printf("Test signal thread finished\n");
return NULL;
}
int main(int argc, char **argv)
{
if(pthread_create(&thread_one_data, NULL, &cond_test_wait, NULL)) {
fprintf(stderr, "Could not create thread, exiting!\n");
return -EXIT_FAILURE;
}
if(pthread_create(&thread_two_data, NULL, &cond_test_signal, NULL)) {
fprintf(stderr, "Could not create thread, exiting!\n");
return -EXIT_FAILURE;
}
pthread_join(thread_one_data, NULL);
pthread_join(thread_two_data, NULL);
pthread_cond_destroy(&condition);
pthread_mutex_destroy(&mutex);
printf("Program ran succesfully!\n");
return -EXIT_SUCCESS;
}
Save in a file cond.c and compile & link using:
gcc -o cond -pthread -Os -Wall cond.c
Do note how neat condition work in this example. You can use them to wait until any expression (= condition) becomes true. After the condition becomes true normal execution continue's.
If you need any more help, don't hesitate to ask in the comments. Good luck combining the above examples to fix up your program.

Resources