刚学semaphores,我就是不明白怎么能让多个线程同时进入资源访问?书本上也没有例子,那位大哥能指点一下啊?不胜感激!最好附带一下应用的例子

解决方案 »

  1.   

    http://www.vckbase.com/document/viewdoc/?id=1708
      

  2.   

    所谓的同时,其实是并发执行的,CPU给每个线程都分配了一定的时间,轮转调度嘛
      

  3.   

    我看了heksn 的关于semaphores的例子,可我以为这样会造成数据错误,那到底semaphores到底何种情况下才适用?
      

  4.   

    比如说一个网站的页面,我们可以设定最大访问量,这个时候我们就可以用到semaphores
      

  5.   

    那么内存数据可不可以使用semaphores呢?我刚才看了一下,如果对某一数组sem[100]采用semaphores,发生了数据错误,怎样使用semaphores才能保证分别输出sem[100]不发生错误呢?
      

  6.   

    semaphores只能用在网站上么?谁能举个内存数组使用semaphores的例子啊?
      

  7.   


    DWORD WINAPI Func1(LPVOID lpParameter);
    int index = 0;
    int a[10]={1,2,3,4,5,6,7,8,9,10}
    CRITICAL_SECTION cSection;int main()
    {
      HANDLE hThread1;
      hThread1 = CreateThread(NULL,0,Func1,NULL,0,NULL);
      CloseHandle(hThread1);  InitializeCriticalSection(&cSection);
      while(index < 10)
        {
          EnterCriticalSection(&cSection);
      index++;
          cout <<"main thread is running - " << index <<endl;
          LeaveCriticalSection(&cSection); // Breakpoint added at this line
        }
      DeleteCriticalSection(&cSection);
      return 0;
    }DWORD WINAPI Func1(LPVOID lpParameter)
    {
      while(index < 10)
        {
          EnterCriticalSection(&cSection);
      index++;
          cout<<a[index]<<endl;
          cout <<"thread1 is running - " << index <<endl;
          LeaveCriticalSection(&cSection);
        }
       
      return 0;

      

  8.   

    semaphores 是 信号量内核对象 主要 是 在 线程 同步 的 时候 使 多个线程 可以 同时 对 数据 进行 访问。