Results 1 to 2 of 2
I'm running the following on linux machine:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
sem_t bin_sem;
char work[1024];
void *f(void *unused)
{
sem_wait(&bin_sem);
while(strncmp("end",work,3) != 0)
{
printf("\n u ...
- 09-09-2007 #1Just Joined!
- Join Date
- Sep 2007
- Posts
- 11
problem in threads execution
I'm running the following on linux machine:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
sem_t bin_sem;
char work[1024];
void *f(void *unused)
{
sem_wait(&bin_sem);
while(strncmp("end",work,3) != 0)
{
printf("\n u input %d char \n",strlen(work)-1);
sem_wait(&bin_sem);
}
pthread_exit(NULL);
}
int main()
{
int res;
pthread_t thId;
void *join_res;
res=sem_init(&bin_sem,0,0);
if(res!=0)
perror("\n semaphore initialization failed \n");
res=pthread_create(&thId,NULL,f,NULL);
if(res!=0)
perror("\n thread creation failed \n");
printf("\n enter data, 'end' to stop \n");
while(strncmp("end",work,3)!=0)
{
if(strncmp("FAST",work,4)==0)
{
sem_post(&bin_sem);
strcpy(work,"Wheeee...");
}
else
{
fgets(work,1024,stdin);
}
sem_post(&bin_sem);
}
printf("\n waiting for thread to finish \n");
res=pthread_join(thId,&join_res);
if(res!=0)
perror("\n join of thread failed \n");
printf("\n thread joined \n");
sem_destroy(&bin_sem);
return 0;
}
the output is as follows:
enter data, 'end' to stop
da
u input 2 char
fdfa
u input 4 char
FAST
u input 8 char
u input 8 char
u input 8 char
end
waiting for thread to finish
thread joined
My question is why the thread-function f() is executing 3 times when I input "FAST"? i've called sem_post() only 2 times in main().
- 09-14-2007 #2Linux User
- Join Date
- Jul 2004
- Location
- Poland
- Posts
- 368
No, you called it 3 times.
HINT: add a printf before you call sem_post, don't forget you call it in two places."I don't know what I'm running from
And I don't know where I'm running to
There's something deep and strange inside of me I see"


Reply With Quote