그래서 1-99 사이의 임의의 값을 갖는 2-d 어레이 [5] [12]를 생성하는 할당이 있습니다. 그런 다음 pthreads를 사용하여 배열의 각 요소에 1을 더하거나 1을 뺀 다음 결과를 출력하고 2, 3 또는 4 스레드로 프로세스를 나눕니다. 스레드의 수는 사용자가 명령 행에서 입력 한 내용에 따라 다릅니다. 컴파일하고 실행하는 코드가 있습니다. 그러나 원하는 출력은 숫자 3을 입력 할 때만 인쇄됩니다. 내가 코드에서 어디서 잘못되었는지 말해 줄 수 있니? 나는 처음에는 pthreads를 이해하는 데 어려움을 겪고 있습니다. 두 번째 루프에서 return 문을 제거하면 생성 된 스레드의 수가 2 인 경우pthread를 사용하여 2-d 어레이를 인쇄하십시오.
#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