Windows线程同步与创建信号量



我正在尝试解决编写器和读取器的问题。我正在尝试使用windows信号灯功能。

它非常简单,如下

      char n[200];
      volatile HANDLE hSem=NULL; // handle to semaphore

控制台的写入功能。释放读取进程的信号量。

     void * write_message_function ( void *ptr )
      {

      /* do the work */
      while(1){
            printf("Enter a string");
            scanf("%s",n);
            ReleaseSemaphore(hSem,1,NULL); // unblock all the threads
        }
      pthread_exit(0); /* exit */
      } 

打印消息等待写入消息的释放以打印消息。

      void * print_message_function ( void *ptr )
      {

       while(1){
            WaitForSingleObject(hSem,INFINITE);
            printf("The string entered is :");
            printf("==== %sn",n);
         }
       pthread_exit(0); /* exit */
      } 

主功能启动应用程序。

     int main(int argc, char *argv[])
     {
     hSem=CreateSemaphore(NULL,0,1,NULL);
     pthread_t thread1, thread2;  /* thread variables */
     /* create threads 1 and 2 */    
     pthread_create (&thread1, NULL, print_message_function, NULL);
     pthread_create (&thread2, NULL, write_message_function, NULL);
     pthread_join(thread1, NULL);
     pthread_join(thread2, NULL);
     /* exit */  
     CloseHandle(hSem); 
     }

程序执行,但不显示字符串输入控制台。

write_message_function中的ReleaseSemaphore将强制执行以下操作:

  1. print_message_function将启动输出
  2. write_message_function将输出并扫描输入

这两件事同时发生。使用信号量触发输出是好的然而,使用MaximumCount=1是对功能的浪费,在输出发生之前,您可能有多个输入。但这里的主要问题是I/O资源和char n[200];的使用实现了线程安全。请参阅"线程安全"代码的含义?详细信息。您仍然需要通过例如mutexcritical section来保护这些资源。

最新更新