在Ubuntu当中使用使用信号量实现线程同步,线程1打印字符a,线程2打印A,依次进行bBcCdD.....
时间: 2023-06-02 12:06:34 浏览: 46
您好!对于您的问题,我可以给您一个参考答案。可以使用两个信号量来控制线程的顺序和同步。
具体步骤如下:
1. 首先创建两个信号量Sem1和Sem2,并分别初始化为0和1。
2. 在线程1中,首先等待Sem1信号量,确保线程2已经先执行,然后打印字母a,再将Sem2信号量加1。
3. 在线程2中,首先等待Sem2信号量,确保线程1已经执行过了,然后打印字母A,再将Sem1信号量加1。
4. 重复步骤2和3,直到打印完所有字母。
代码示例:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t Sem1, Sem2; // 定义两个信号量
void *thread1(void *arg)
{
int i;
for (i = 0; i < 26; i++) {
sem_wait(&Sem2); // 等待Sem2
printf("%c", 'a' + i);
fflush(stdout);
sem_post(&Sem1); // 发送Sem1
}
pthread_exit(NULL);
}
void *thread2(void *arg)
{
int i;
for (i = 0; i < 26; i++) {
sem_wait(&Sem1); // 等待Sem1
printf("%c", 'A' + i);
fflush(stdout);
sem_post(&Sem2); // 发送Sem2
}
pthread_exit(NULL);
}
int main()
{
pthread_t t1, t2;
sem_init(&Sem1, 0, 0); // 初始化Sem1为0
sem_init(&Sem2, 0, 1); // 初始化Sem2为1
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&Sem1); // 销毁Sem1
sem_destroy(&Sem2); // 销毁Sem2
return 0;
}
希望这个答案对您有所帮助!如果您有其他问题,欢迎随时提出。