編寫一個程序,開啓3個線程,這3個線程的ID分別爲A、B、C,每個線程將自己的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示;如:ABCABC…依次遞推。
- 使用pthread_join進行阻塞,等對應的id線程運行結束再往下運行
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
pthread_mutex_t mutex;
void ThreadProc(void* arg)
{
char *str = (char*)arg;
printf("%s", str);
}
int main()
{
pthread_t id;
int i = 0;
for (i = 0; i<10; i++)
{
pthread_create(&id, NULL, (void*)ThreadProc, "A");
pthread_join(id, NULL);
pthread_create(&id, NULL, (void*)ThreadProc, "B");
pthread_join(id, NULL);
pthread_create(&id, NULL, (void*)ThreadProc, "C");
pthread_join(id, NULL);
}
printf("\n");
return 0;
}
- 使用sem信號量PV互斥操作,來達到輸出
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <semaphore.h>
sem_t sem1;
sem_t sem2;
void ThreadProc1(void* arg)
{
char *str = (char*)arg;
sem_wait(&sem1);
printf("%s", str);
sem_post(&sem2);
}
void ThreadProc2(void* arg)
{
char *str = (char*)arg;
sem_wait(&sem2);
printf("%s", str);
}
void ThreadProc3(void* arg)
{
char *str = (char*)arg;
sem_post(&sem1);
printf("%s", str);
}
int main()
{
sem_init(&sem1, 0, 0);
sem_init(&sem2, 0, 0);
pthread_t id1, id2, id3;
int i = 0;
for (i = 0; i<10; i++)
{
pthread_create(&id1, NULL, (void*)ThreadProc1, "B");
pthread_create(&id2, NULL, (void*)ThreadProc2, "C");
pthread_create(&id3, NULL, (void*)ThreadProc3, "A");
pthread_join(id2, NULL);
}
sem_destroy(&sem1);
sem_destroy(&sem2);
printf("\n");
return 0;
}