对于州,我是一个学生谁不是一个CS大学毕业生,但正在进入一个CS硕士。因此,我欢迎任何人愿意给予的一切帮助。
这样做的目的是在2-4之间创建N个线程,然后使用一个随机生成的小写字符数组,使其大写。
这需要使用N个线程来完成(在执行时由命令行定义),尽可能均匀地使用p线程将工作分割开来。
我想问的主要问题是,我是否避免了线程之间的竞争条件?
我也在努力理解如何在线程间划分工作。正如我所理解的(如果我错了,请纠正我的错误),一般来说,在执行过程中,运行中的线程将被随机选择。所以,我假设我需要做一些事情,在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;
}发布于 2018-03-18 07:43:16
您提供的示例不是一个好的多线程程序。原因是您的线程将不断等待持有锁的线程。基本上你的程序是连续的。我会把你的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的值、增量它并释放锁,然后执行其余的操作。
一般规则是,只有在处理关键部分或关键数据(本例中是字符串的索引)时,才能获得锁。阅读有关关键部分和赛车条件的这里
https://stackoverflow.com/questions/49342219
复制相似问题