2017-04-17 5 views
0

여러 스레드를 이해하는 데 어려움이 있습니다. 여기에 상황이 있습니다 :C에서 pThread를 사용하여 여러 스레드와 배열 비교

배열에서 정수를 선택하고 조건에 따라 다른 배열에 저장하려고합니다. 조건은 매우 복잡합니다. 기본적으로 array [i]와 다른 모든 배열 [not i] 사이의 커다란 비교 집합입니다. 그것을 checkCondition()이라고 부르 자.

먼저 pthread를 만듭니다. 여기 내 코드입니다, dataPackage 배열을 포함하는 구조체 것을 지적했다. 여기

for(int i = 0; i < thread_number; i++){ 
    if(pthread_create(&tid, NULL, checkPermissible, &dataPackage) != 0){ 
     perror("Error occurs when creating thread!!!\n"); 
     exit(EXIT_FAILURE); 
    } 
} 

for(int i = 0; i < thread_number; i++){ 
    pthread_join(tid, NULL); 
} 

는 checkPermissible의 내용() 나는이 작업을 수행 pthread와 방법을 사용하지 않는 경우

void* checkPermissible(void* content){ 
    readThread *dataPackage = content; 

    for(int i = 0; i < (*dataPackage).arrayLength; i++){ 
     if(checkCondition()){ 
      pthread_mutex_lock(&mutex); 
      insert(array[i], (*dataPackage).result); 
      pthread_mutex_unlock(&mutex); 
      //if condition true, insert it into result(a pointer) 
      //mutex avoid different thread insert the value at the same time 
     } 
    } 

    pthread_exit(NULL); 
} 

그러나, 그것은 어떤 차이가없는 것입니다. checkPermissible()을 구현하여 다중 스레드의 이점을 이끌어 내기 위해서는 어떻게해야합니까? 나는이 물건에 대해 아주 혼란스러워했다.

제 아이디어는 배열을 각 스레드에서 noOfThread로 나누는 것입니다. 예를 들어 배열 [20]과 스레드 4 개가 있습니다.

Thread 1: compute checkCondition with array[0] to array[4] 
Thread 2: compute checkCondition with array[5] to array[9] 
Thread 3: compute checkCondition with array[10] to array[14] 
Thread 4: compute checkCondition with array[15] to array[19] 

달성 방법을 모르겠다. 다음과 같이

+0

checkCondition은 cpu 강렬한 연산입니까? 그렇지 않은 경우 멀티 스레딩을 전혀 사용하지 않는 것이 좋습니다. – klutt

+0

아니요, 그렇지 않습니다. 멀티 스레딩을 사용하는 것이 필요하며 속도를 향상시키는 것이 중요하다고 생각합니다. – Hugo

+0

하지만 문제가 무엇입니까? 작동합니까? 게시물에 명확한 질문이 없습니다. – klutt

답변

1

첫째, 당신은 당신의 구조에 스레드 하부 및 상부 경계 또는 주소를 전달할 수 있습니다

struct readThread { 
    int low; 
    int hi; 
    int * myarray; 
}; 

for (int i=low;i<hi;++i) 

//or 

struct readThread { 
    int * start; 
    int * end; 
}; 

for (int* i=start; i<end; ++i) 

우선 하나는 쉽게뿐만 아니라 이해하기 쉽다. 이 방법으로 배열이 분할됩니다.

각 스레드에 대해 오류의 분할 사본을 만드는 것과 같은 다른 방법이 있습니다.

+0

고마워요 !!! 그게 내가 원하는거야! – Hugo