所以我有一個任務,說我已經創建了一個二維數組[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