2011-02-08 58 views
0

我很好奇,如果我實現這個正確的使用信號量。我希望clientThread只有在serverThread完成後才能執行。
我當前的代碼給我一個錯誤(不編譯/連接錯誤)與「關閉程序」(只有當我在clientThread打印)這裏是我的代碼:使用posix semphores問題

void* serverThread(void* sock) 
{ 
    sem_wait(&mutex); 
    Handle handle((TCPSocket*)sock); 
    handle.HandleAuthentication(); 
    sem_post(&mutex); 
    sem_post(&mutex2); 
} 

void* clientThread(void* sock) 
{ 
    sem_wait(&mutex2); 
    cout << "Address is: -> " << Handle::getAddress() << " ------ " << Handle::getPort() << endl; 
    sem_post(&mutex2); 
} 

int main() 
{ 
    sem_init(&mutex, 0, 1); 
    sem_init(&mutex2, 0, 0); 
    unsigned short echoServPort = 9898; 

    try { 
     TCPServerSocket servSock(echoServPort); 

     for (;;) { 
      TCPSocket* sock = servSock.accept(); 
      pthread_t pidClient, pidServer; 
      if(pthread_create(&pidServer, NULL, serverThread, (void*)sock) != 0) 
      { 
       throw SocketException("Unable to create server thread (pthread_create()", true); 
      } 
      if(pthread_create(&pidClient, NULL, clientThread, NULL) != 0) 
      { 
       throw SocketException("Unable to create client thread (pthread_create()", true); 
      } 
     } 
    } catch (SocketException &e) { 
     cerr << e.what() << endl; 
     exit(1); 
    } 
    return 0; 
} 

編輯: 這是檢查後錯誤使用gdb:

(gdb) bt 
#0 0x6fcb6afb in libstdc++-6!_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES 
5_PKc() from c:\MinGW\bin\libstdc++-6.dll 
#1 0x0040146d in _fu0___ZSt4cout (sock=0x0) at ..\src\client.cpp:212 
#2 0x6e0c5121 in [email protected]() from c:\MinGW\bin\libpthread-2.dll 
#3 0x76e01287 in msvcrt!_itow_s() from C:\Windows\system32\msvcrt.dll 
#4 0x76e01328 in msvcrt!_endthreadex() from C:\Windows\system32\msvcrt.dll 
#5 0x76cb1174 in KERNEL32!AcquireSRWLockExclusive() 
    from C:\Windows\system32\kernel32.dll 
#6 0x76efb3f5 in ntdll!RtlInsertElementGenericTableAvl() 
    from C:\Windows\system32\ntdll.dll 
#7 0x76efb3c8 in ntdll!RtlInsertElementGenericTableAvl() 
    from C:\Windows\system32\ntdll.dll 
#8 0x00000000 in ??() 

回答

1

我看到一個循環,你的代碼,所以你可能是指類似:

void* serverThread(void* sock) 
{ 
    sem_wait(&empty); 
    Handle handle((TCPSocket*)sock); 
    handle.HandleAuthentication(); 
    sem_post(&full); 
} 

void* clientThread(void* sock) 
{ 
    sem_wait(&full); 
    cout << "Address is: -> " << Handle::getAddress() << " ------ " << Handle::getPort() << endl; 
    sem_post(&empty); 
} 

int main() 
{ 
    sem_init(&full, 0, 0); 
    sem_init(&empty, 0, 1); 
    ... 

如果您計劃崩潰,那麼最好用-O0 -g進行編譯,並在gdb下運行以檢查堆棧跟蹤。

或者您可以在shell中執行ulimit -c unlimited,以便核心文件自動創建。

+0

是的,yor代碼比較好,thanx,現在我仍然需要找出它崩潰的原因 – Kobe 2011-02-08 21:32:58