gpt4 book ai didi

c - 试图理解 C 中的竞争条件/线程

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:29 27 4
gpt4 key购买 nike

对于陈述者,我不是 CS 本科生,但正在攻读 CS 硕士。因此,我欢迎任何愿意提供帮助的人。

这样做的目的是在 2-4 之间创建 N 个线程,然后使用随机生成的小写字符数组,将它们变成大写。

这需要使用 N 个线程(执行时由命令行定义)来完成,使用 pthread 尽可能平均地分配工作。

我想问的主要问题是,我是否避免了线程之间的竞争条件?

我也在努力理解线程之间的工作分配。据我了解(如果我错了请纠正我),通常在执行期间会随机选择运行的线程。所以,我假设我需要做一些事情,在 N 个线程之间动态划分数组并设置它,以便每个线程将执行数组相同大小的子部分的大写?

我知道我的代码中可能还有许多其他差异需要改进,但我的编码时间不长,大约一个月前才开始使用 C/C++。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <ctype.h>

//Global variable for threads
char randChars[60];
int j=0;

//Used to avoid race conditions
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

//Establish the threads
void* upperThread(void* argp)
{
while(randChars[j])
{
pthread_mutex_lock( &mutex1 );
putchar (toupper(randChars[j]));
j++;
pthread_mutex_unlock( &mutex1 );
}

return NULL;

}

int main(int argc, char **argv)
{
//Initializae variables and thread
int N,randNum,t;
long i;
pthread_t pth[N];
pthread_mutex_init(&mutex1, NULL);
char randChar = ' ';

//Check number of command inputs given
if(argc!=2)
{
fprintf(stderr,"usage: %s <enter a value for N>\n", argv[0]);
exit(0);
}

N = atoi(argv[1]);

//Checks command inputs for correct values
if(N<2||N>4){
printf("Please input a value between 2 and 4 for the number of threads.\n");
exit(0);
}

//Seed random to create a randomized value
srand(time(NULL));
printf("original lower case version:\n");

for (i=0; i<61; i++)
{
//Generate a random integer in lower alphabetical range
randNum = rand()%26;
randNum = randNum+97;

//Convert int to char and add to array
randChar = (char) randNum;
randChars[i] = randChar;
printf("%c", randChar);
}

//Create N threads
for (i=0; i<N; i++)
{
pthread_create(pth + i, NULL, upperThread, (void *)i);
}

printf("\n\nupper case version:\n");

//Join the threads
for(t=0; t < N; t++)
{
pthread_join(pth[t], NULL);
}
printf("\n");

pthread_exit(NULL);

return 0;
}

最佳答案

您提供的示例不是一个好的多线程程序。原因是您的线程将不断等待持有锁的线程。这基本上使您的程序顺序。我会将您的 upperThread 更改为

void* upperThread(void* argp){
int temp;
while(randChars[j]){
pthread_mutex_lock( &mutex1 );
temp = j;
j++;
pthread_mutex_unlock( &mutex1 );

putchar (toupper(randChars[temp]));
}

return NULL;

}

这样您的线程将等待一个持有锁的线程,直到它提取 j 的值,递增它并释放锁,然后执行其余操作。

一般规则是只有在处理临界区临界数据 时才需要获取锁,在这种情况下它是字符串的索引。阅读有关关键部分和赛车条件的信息 here

关于c - 试图理解 C 中的竞争条件/线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com