c - 如何在 C 中使用 pthread 交替 5 个 0 值和 5 个 1 值?
问题描述
我有一个使用 C 语言的小任务,它填充一个大小为 30 的整数数组,交替 5 个值 0(由一个线程编写)和 5 个 1 值(由第二个线程编写)。
到目前为止,这是我的代码:
#include <stdio.h>
#include <pthread.h>
int count = 0;
int oktogo = 1; //0 is false, 1 is true. For thread2 this is reversed.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
void *start_thread_one()
{
int i;
for (i=1;i<30;i++) {
pthread_mutex_lock(&mutex);
while (oktogo == 0)
pthread_cond_wait(&condition, &mutex);
count=0;
printf("thread one: %d\n", count);
oktogo = 0;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
pthread_exit(0);
}
void *start_thread_two()
{
int i;
for(i=1;i<30;i++) {
pthread_mutex_lock(&mutex);
while (oktogo == 1)
pthread_cond_wait(&condition, &mutex);
count =1;
printf("thread two: %d\n", count);
oktogo = 1;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
pthread_exit(0);
}
int main ()
{
int count = 0;
pthread_t p1,p2;
pthread_create(&p1,NULL,(void *)start_thread_one,NULL);
pthread_create(&p2,NULL,(void *)start_thread_two,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
return(0);
}
输出只显示线程一的值为 0,然后线程二的值为 1。如何交替打印出 5 个 0 值和 5 个 1 值,而不是一个一个地打印出来?
截图:
解决方案
您的线程同步逻辑似乎很好。
唯一的问题是,当您有机会 [并让主线程] 在加入线程后将其打印出来时,您实际上并没有将其存储到数组中。
此外,您实际上并不需要两个单独的线程函数。您可以使用单个参数/值为 0 或 1。也就是说,arg 指定线程数组的起始偏移量以及要存储的值和所需的值oktogo
。
无论如何,这是一个工作版本:
#include <stdio.h>
#include <pthread.h>
int count = 0;
int oktogo = 0; // 0 is false, 1 is true. For thread2 this is reversed.
#define CHUNK 5
int array[5000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
void *
start_thread(void *ptr)
{
long self = (long) ptr;
int i;
for (i = 1; i < 30; i++) {
pthread_mutex_lock(&mutex);
while (oktogo != self)
pthread_cond_wait(&condition, &mutex);
printf("thread %ld: %d\n",self,count);
for (int idx = 0; idx < CHUNK; ++idx, ++count)
array[count] = self;
oktogo = ! self;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
pthread_exit(0);
}
int
main()
{
int count = 0;
pthread_t p1,
p2;
for (int idx = 0; idx < sizeof(array) / sizeof(array[0]); ++idx)
array[idx] = -1;
pthread_create(&p1, NULL, (void *) start_thread, (void *) 0);
pthread_create(&p2, NULL, (void *) start_thread, (void *) 1);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
for (int idx = 0; idx < sizeof(array) / sizeof(array[0]); ++idx) {
if (array[idx] >= 0)
printf("%d: %d\n",idx,array[idx]);
}
return (0);
}
推荐阅读
- linux - 如何在 Linux 中更改单个线程的名称?
- django - Django-REST-Framework 验证失败:“此字段是必需的”
- java - Spring Boot @Insert 一个实体,其属性是自定义对象
- mendix - Mendix 检索最后一个输入值
- git - 当您在本地计算机上使用 git 提交时,您是否会在关闭计算机时丢失分支/提交?
- c++ - 当从 setter 方法返回 *this 时,对象变得不可变
- mysql - 如何在 MySQL 中执行 2 Order By 子句?
- flutter - 在颤动中删除标题和圆环图和图例之间的额外空格
- android - Android Coordinator Layout - 无法将按钮与底部对齐
- javascript - 加载组件时未检查角度单选按钮