#include <stdio.h>
#include <string.h>
#include<unistd.h>
#include<semaphore.h>
#include<pthread.h>
#include <stdlib.h>
void exit_sys(const char* msg);
void exit_sys_result(const char *msg,int result);
void *thread_proc1(void *param);
void *thread_proc2(void *param);
void do_something(const char *msg);
sem_t g_sem;
int main(void)
{
printf("Hello World!\n");
int result;
pthread_t tid1,tid2;
srand(time(NULL));
if(sem_init(&g_sem,0,1)==-1)
{
exit_sys("sem_init");
}
if((result=pthread_create(&tid1,NULL,thread_proc1,NULL))!=0)
{
exit_sys_result("thread create1",result);
}
if((result=pthread_create(&tid2,NULL,thread_proc2,NULL))!=0)
{
exit_sys_result("thread create2",result);
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&g_sem);
return 0;
}
void *thread_proc1(void *param)
{
int i;
for(i=0;i<10;i++)
{
do_something(" thread-1 ");
}
return NULL;
}
void *thread_proc2(void *param)
{
int i;
for(i=0;i<10;i++)
{
do_something(" thread-2 ");
}
return NULL;
}
void do_something(const char *str)
{
sem_wait(&g_sem);
printf("-----------------------\n");
printf("%s: Step-1\n",str);
usleep(rand()%300000);
printf("%s: Step-2\n",str);
usleep(rand()%300000);
printf("%s: Step-3\n",str);
usleep(rand()%300000);
printf("%s: Step-4\n",str);
usleep(rand()%300000);
printf("%s: Step-5\n",str);
usleep(rand()%300000);
sem_post(&g_sem);
}
void exit_sys(const char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
void exit_sys_result(const char *msg, int result)
{
fprintf(stderr, "%s: %s\n", msg, strerror(result));
exit(EXIT_FAILURE);
}