使用C中的线程无限打印1 2 3
在这里,我们必须使用c编程语言中的线程无限次地重复打印123序列。
让我们看一下我们想要的代码示例输出,
123123123123
为此,我们将不得不使用在C编程语言中并排运行的三个线程。在第一个线程中初始化为一个的变量,其值将根据其最后一个值进行更新。并在函数中运行无限循环。
示例
让我们看一下实现我们的解决方案的程序,
#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int value = 1;
void *foo(void *n){
while(1) {
pthread_mutex_lock(&lock);
if (value != (int)*(int*)n) {
if ((int)*(int*)n == 1) {
pthread_cond_wait(&cond1, &lock);
} else if ((int)*(int*)n == 2) {
pthread_cond_wait(&cond2, &lock);
} else {
pthread_cond_wait(&cond3, &lock);
}
}
printf("%d ", *(int*)n);
if (value == 3) {
value = 1;
pthread_cond_signal(&cond1);
}
else if(value == 1) {
value = 2;
pthread_cond_signal(&cond2);
} else if (value == 2) {
value = 3;
pthread_cond_signal(&cond3);
}
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main(){
pthread_t tid1, tid2, tid3;
int n1 = 1, n2 = 2, n3 = 3;
pthread_create(&tid1, NULL, foo, (void *)&n1);
pthread_create(&tid2, NULL, foo, (void *)&n2);
pthread_create(&tid3, NULL, foo, (void *)&n3);
while(1);
return 0;
}输出结果
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3….
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练