2012-07-03 4 views
1

아래의 내 의사 코드를 참조하십시오. 코드 주석이 내 문제를 설명해야합니다. 나는 pthread와 C의 링크드리스트에 익숙하지 않아서 깊은 곳으로 뛰어 들었습니다. 그냥 thread_work 함수에서 str 값을 출력해야합니다. 순차 코드 비트는 괜찮지 만 각 스레드가 작업 할 때 str 값을 인쇄 할 수 없습니다. 내 실제 코드에서연결된 목록 노드를 pthread 함수에 올바르게 전달

// linked list definition 
struct linked_list { 
    char *str; 
    struct linked_list *next; 
}; 

// linked list initiation 
struct linked_list *root; 
struct linked_list *next_info; 
root = malloc(sizeof(struct linked_list)); 

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) &next_node); 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node = next_node->next; 
} 

// code executed by each thread 
void *thread_work(void *thread_arg) { 
    struct linked_list *ll; 
    ll = (struct linked_list *)thread_arg; 
    printf("%s\n", ll->str); // PRINTS SOME MESS (��E#) 
} 

linked_liststruct의 몇 가지 더 많은 회원이 있습니다.

감사합니다.

+1

그냥 참고 : 당신은하지의 주소, next_node의 값을 전달해야 thread_arg'은''무효 * 인'때문에, 다른 데이터 포인터 형식으로 변환 할 때 캐스팅 절대적으로 필요가있다. 'struct linked_list * ll = thread_arg; "'. – unwind

답변

2

포인터 유형이 일치하지 않습니다. 목록 노드에 대한 포인터에 포인터를 전달하고 있지만 thread_work 안에는 포인터를 노드에 대한 포인터로 처리합니다. 어느 pthread_create에 호출 next_node 전에 앰퍼샌드를 제거하거나 다음과 같이 thread_work을 변경 printf("%s\n", next_node) 잘 작동

void *thread_work(void *thread_arg) { 
    struct linked_list **llp, *ll; 
    llp = (struct linked_list **)thread_arg; 
    ll = *llp; 
    printf("%s\n", ll->str); // PRINTS SOME GOOD STUFF 
} 
+0

고맙습니다. 최소 시간이 만료 된 것으로 풀이 표시하겠습니다. – ale

0

경우, next_node 포인터가 및 그 당신이 는 pthread_create에 포인터에 지점을 schouldn't().이 좋은 것 next_node의 정의)

이 코드는 나쁜 rc = pthread_create(&thread, NULL, thread_work, (void *) next_node);

0

을 시도 :

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) &next_node); 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node = next_node->next; 
} 

여기서 문제는 그 즉시 값이 변경 변수에 대한 포인터를 전달하는 것입니다 pthread_create로 전화 한 후 OS가 새로운 스레드로 프로세스를 복제하는 데 약간의 시간이 걸리므로 은 next_node = next_node->next; 문이 실행 된 후 시작될 수 있으며 (대부분의 경우) next_node의 잘못된 값을 선택합니다.

// main code 
some loop { 
    next_node->str = str; 
    printf("%s\n", next_node->str); // PRINTS FINE 
    pthread_t thread; 
    rc = pthread_create(&thread, NULL, thread_work, (void *) next_node); 
    // Store this thread handle somewhere safe to be able to join the thread later on 
    next_node->next = malloc(sizeof(struct linked_list)); 
    next_node->next->str = next_node->next->next = NULL; // Always a good idea 
    next_node = next_node->next; 
}