所以我有一个任务,说我已经创建了一个二维数组[5] [12],随机值在1-99之间。然后使用pthreads,我必须为数组中的每个元素加1或减1,然后打印结果并将进程分成2,3或4个线程。线程的数量取决于用户在命令行上输入的内容。我有编译和运行的代码。但是,我希望的输出仅在输入数字3时打印。你能告诉我我的代码出错了吗?我在开始时无法理解pthread。使用pthread打印二维数组
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <pthread.h>
#include <iostream>
using namespace std;
int list[5][12];
int rows = 5;
int cols = 12;
int threadc;
void *threadf(void *arg)
{
int x = (int) arg;
for(int i = (x*60)/threadc; i < ((x+1) * 60)/threadc; i++)
{
for(int j = 0; j < 12; j++)
{
if (list[i][j] % 2 == 0)
list[i][j] += 1;
else
list[i][j] -= 1;
}
}
}
void cArray()
{
srand(time(NULL));
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 12; j++)
{
list[i][j] = rand() % 99 + 1;
}
}
}
void pArray(int list[][12], int rows, int cols)
{
cout << "\n";
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << list[i][j] << " ";
}
cout << "\n";
}
}
int main(int argc, char *argv[])
{
if(argc != 2) exit(0);
threadc = atoi(argv[1]);
assert(threadc >= 2 && threadc <=4);
pthread_t *thread;
thread = new pthread_t [threadc];
if(thread == NULL)
exit(0);
cArray();
cout << "2-d Array: ";
pArray(list, rows, cols);
int t;
for(int i = 0; i < threadc; i++)
{
t = pthread_create(&thread[i], NULL, threadf, (void *)i);
if (t != 0)
return 1;
}
for(int i = 0; i < threadc; i++)
{
t = pthread_join(thread[i], NULL);
if(t != 0)
return 1;
}
cout << "Modified 2-d Array: ";
pArray(list, rows, cols);
return 0;
}
这是一个家庭作业? – hmatar
是的。这是不允许的吗? –
这是允许的,到目前为止,它看起来像你展示你的工作。尽管推荐一些更改:“我的期望输出”显示此。同时显示你正在得到的东西。建议:开始时不要使用随机数字,这样您就可以一遍又一遍地测试相同的数字,直到您将线程整理出来。更容易找出改进或错误。 – user4581301