다중 쓰레드 사용시 작동이 이상합니다.

kkw90111의 이미지

간단한 다중 쓰레드 예제 작성중에 이해가지 않는 부분이 있어 질문 올립니다.

2개의 자식 쓰레드를 만들어서 첫번째 쓰레드는 A를 찍고 두번째 쓰레드는 B를 찍고 부모 쓰레드는 기다린 후에 메세지를 출력하는 프로그램입니다.
근데 반복하는 횟수가 적을땐 잘돌아가니 십더니 100을 넘어서면서 부터 이상이 생깁니다.
우선 A와 B가 찍히는 개수가 100이 되지 않습니다. 원래 대로라면 A가 100번 B가 100번 해서 총 200번이 찍혀야 하는데 많이 모자랍니다.
루프를 10000번 까지도 돌려봤는데 역시나 몇번 찍히지 않습니다.
그래서 어떻게 실행되는지 보려고 count 변수를 하나 넣어 출력해 보았더니 더더욱 이상한 현상이 생기더라구요...ㅠ
루프 횟수를 100으로 줬을때,
[97]I'm chile_2 [B]
[98]I'm child_1 [A]
[99]I'm child_1 [A]
[100]I'm chile_2 [B]
[100]I'm child_1 [A]
[100]I'm child_1 [A]
[100]I'm chile_2 [B]
[100]I'm child_1 [A]
[100]I'm chile_2 [B]
[100]I'm child_1 [A]
[100]I'm chile_2 [B]
[100]I'm child_1 [A]

이런식으로 출력이 됩니다... 중요한건 이것 역시 100번을 반복으로 줬는데 총 50개도 안찍혀 나옵니다.
어디가 잘못 된건지 알 수 있을까요.... count 변수는 i 변수랑 똑같지만 구지 구별하려고 또 넣었습니다.

#include<stdio.h>
#include<pthread.h>
 
int func1(void);
int func2(void);
 
int i = 0;
int count = 0;
 
int main(int argc, char* argv[])
{
        void *tret;
 
        pthread_t id1;
        pthread_t id2;
 
        while(i < 100) {
                pthread_create(&id1, NULL, func1, NULL);
                pthread_create(&id2, NULL, func2, NULL);
                count++;
                i++;
        }
 
        pthread_join(id1, &tret);
        pthread_join(id2, &tret);
 
        printf("\n==My children have gone==\n");
        return 0;
}
 
int func1(void) {
        printf("[%d]I'm child_1 [A]\n",count);
        return 0;
}
 
int func2(void) {
        printf("[%d]I'm chile_2 [B]\n",count);
        return 0;
}
kkw90111의 이미지

밑 부분소스가 이상하게 깨지네요.. 어떻게 수정 하는지 모르겠네요;;;
밑 부분 소스만 다시 올립니다.

int func1(void) {
        printf("[ %d ] I'm child_1 [A]\n",count);
        return 0;
}
 
int func2(void) {
        printf("[ %d ] I'm chile_2 [B]\n",count);
        return 0;
}
hsnks100의 이미지

pthread_create 리턴값이 올바르게 리턴되는지 확인해주세요. 몇번 실패할지도 모르겠네요..

----------------------------------------------------
개인 블로그: https://kangssu.com

kkw90111의 이미지

제가 지금 밖이라 확인은 이따 확인 해야 될 것 같은데
실패한다면 왜 실패하는거죠?... 특별한 문제는 없는 것 같은데요..

cssddd3의 이미지

while을 돌면서 쓰레드를 동작시키지만 정작 쓰레드가 수행되는덴 시간이 걸려서 중간에 끈키고 while문은 count랑 i 값을 증가시키고
다시 CPU가 이전에 수행하다만 쓰레드를 마져 수행시키려 하면 이미 메모리에 count랑 i의 값은 증가되어있는거죠..

kkw90111의 이미지

그럼 while 문 안에 2개의 쓰레드 호출하고 sleep를 넣어줘야하나요??

cssddd3의 이미지

저도 위의 쓰레드 함수를 써보지는 않았습니다만 ...
락을 걸어야 제대로 동작할거 같네요

sunyzero의 이미지

1. 쓰레드는 비순차, 비결정적입니다. 코드 순서대로 작동한다는 보장이 없습니다.
2. 그리고 구조적인 문제로는 쓰레드는 200개가 생성되는데, join은 2번 뿐이네요?

전체적으로 설계나 의도가 잘못 작성된 예제입니다.

========================================
* The truth will set you free.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.