win32 semaphore synchronize

서지훈의 이미지

win32 환경에서 semaphore 를 이용해서 아래와 같은 출력이 가능했으면 합니다.

parent_0
child_0
parent_1
child_1
parent_2
child_2
 
...
 
parent_9
child_9

아무리 머리를 쥐어 짜도 방법이 ? ...
혹 semaphore 가 아니더라도 서로 완전히 독립된 process(thread)에서 이런 작동이 가능한 방법도 환영합니다.

음... 역시 *nix 에서 주로 하다 win32환경에서 할려니 다른 환경과 무지에 힘드네요.

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

dionysos의 이미지

다른 Process나 아니면 쓰래드에서도 사용가능한것 같은데요.

Main : print로 출력 -> 이벤트로 깨움(쓰래드나 프로세스) -> 이벤트를 기다림 ## 반복
sub : 이벤트기다림 -> print로 출력 -> 이벤트로 깨움 ## 반복

이렇게 하시면 아마 될꺼 같습니다.

그리고 여기에다 Semaphore를 추가하시면 조금더 괜찮은 코드를 만드실수 있을겁니다.

노력은 배반하지 않는다.

노력은 배반하지 않는다.

체스맨의 이미지

실은 질문 내용이 무엇을 원하는 것인지 잘 이해가 되지 않습니다. -_-;

하지만, pthread win32 포트( http://sourceware.org/pthreads-win32/ )도 있고,
윈도 동기화 개체도 기본적으로 유닉스의 것과 크게 다르지 않기 때문에 잘 살펴보시면
원하시는 것을 구현하실 수 있을 거라 생각됩니다.

Orion Project : http://orionids.org

서지훈의 이미지

일단 제가 하고자 하는 것은 완전히 독립된 process에서 완전 동기화된 작업이 가능하게 하고 싶은 것입니다.
그냥 win32 semaphore를 사용할 경우는 무조건 먼저 잡는 놈이 장땡이기 때문에 동기화가 힘들더군요.
*nix 에서는 두개의 프로세스의 경우 semaphore에서 wait operation을 이용해서 서로 반복작업이 가능한데 win32에서는 이게 없어서...
참고: SystemV semaphore

    if ((pid = fork())) { /* parent */
        for (i = 0; i &lt; 10; ++i) {
            printf("AAAA\n\n");
            LOCK(); /* sem_op = -1 */
            printf("parent: critical region.\n");
        }
    }
    else { /* child */
        for (i = 0; i &lt; 10; ++i) {
            WAITING();  /* sem_op = 0 */
            printf("child : critical region.\n");
            UNLOCK();  /* sem_op = 1 */
        }
 
        remove_sem();
        exit(0);
    }

아무래도 자료를 더 찾아 봐야 할듯 합니다.

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

#include <com.h> <beer.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

체스맨의 이미지

원하신는 걸 정확히 구현했는지는 모르겠지만, 대개는 두개의 동기화 개체를 이용하면 될 것이라 생각합니다. 저는 1개의 세마포어와 1개의 이벤트 개체를 이용했습니다. ( 두개의 이벤트 개체 또는 두개의 세마포어로도 가능합니다. ) 윈도에 포크가 없으니, 인자가 있는 CreateProcess 로 대체했습니다.

#include <stdio.h>
#include <memory.h>
#include <limits.h>
#include <windows.h>
 
int
main( int argc, char* argv[] )
{
    HANDLE sem, evt;
    int i;
    static char cmd[256];
    static const char semname[] = "semtest", evtname[] = "evttest";
 
    if( argc<2 ) {
        static STARTUPINFO si;
        static PROCESS_INFORMATION pi;
 
        sem = CreateSemaphore( NULL, 1, LONG_MAX, semname );
        evt = CreateEvent( NULL, FALSE, FALSE, evtname );
 
        /* fork a new process */
        GetModuleFileName( NULL, cmd, sizeof(cmd) );
        memset( &si, 0, sizeof(STARTUPINFO) );
        si.cb = sizeof(STARTUPINFO);
        strcat( cmd, " 1" );
        CreateProcess( NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi );
        for( i=0; i<10; i++ ) {
            printf( "AAAA\n" );
            WaitForSingleObject( sem, INFINITE );
            printf( "parent : critical region.\n" );
            SetEvent( evt );
        }
    }
    else {
        sem = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE, semname );
        evt = OpenEvent( EVENT_ALL_ACCESS, FALSE, evtname );
        for( i=0; i<10; i++ ) {
            WaitForSingleObject( evt, INFINITE );
            printf( "child : critical region.\n" );
            ReleaseSemaphore( sem, 1, NULL );
        }
    }
    CloseHandle( evt );
    CloseHandle( sem );
    return 0;
}
 
 
/* EOF */

Orion Project : http://orionids.org

체스맨의 이미지

어차피 producer-consumer 문제 아닌가요...? 세마포어 두개 쓰는...

Orion Project : http://orionids.org

서지훈의 이미지

체스맨님 덕분에 잘 해결이 된듯 하네요.
딱 제가 원하든것 ^^;;;
그럼... 즐거운 오후 되세요 ~ !

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

#include <com.h> <beer.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.