编写一个程序,开启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;
}