vc++多线程编程

来源:互联网 发布:js math保留两位小数 编辑:程序博客网 时间:2024/04/29 10:46

vc++中的多线程编程:

HANDLE hMutex; // Create a mutex with no initial owner. 必须要创建一个句柄
hMutex = CreateMutex( NULL, // no security attributes 
                               FALSE, // initially not owned 
"MutexToProtectDatabase"); // name of mutex 
//这个句柄只想信号量,第一个参数一半为NULL,第二个(初始化时是否被获得)false为现在可以被任何人使用
//第三个参数是为信号量起名,方便以后查找该信号量
if (hMutex == NULL) 

    
// Check for error.一般不必这样用。 
}
 

 

 

BOOL FunctionToWriteToDatabase(HANDLE hMutex) 

    DWORD dwWaitResult; 
// Request ownership of mutex.
    dwWaitResult = WaitForSingleObject( 
                                           hMutex, 
// handle to mutex 
                                           5000L); // five-second time-out interval 
        switch (dwWaitResult) 
            
// The thread got mutex ownership. 
            case WAIT_OBJECT_0: 
                 __try 

                         
// Write to the database. 
                 }
 
                 __finally 

                         
// Release ownership of the mutex object. 
                 if (! ReleaseMutex(hMutex)) 
                         
// Deal with error. 
                 }
 
                 
break; }
 
                 
// Cannot get mutex ownership due to time-out.
                 case WAIT_TIMEOUT: 
                      
return FALSE; 
                      
// Got ownership of the abandoned mutex object. 
                 case WAIT_ABANDONED: 
                      
return FALSE; 
           }
 
      
return TRUE; 
}

 

DWORD dwWaitResult 只是为了判断信号量的归谁所有。 WaitForSingleObject() 相当与P()操作,参数有两个:第一个是信号量,第二个是等待时间。INFINITE代表无限等待。5000L代表等待5秒,如果5秒内获得信号量,dwWaitResult== WAIT_OBJECT_0,如果5秒没有得到信号量,则dwWaitResult== WAIT_TIMEOUT,而WAIT_ABANDONED代表操作失败。 ReleaseMutex(hMutex)相当于V()操作。参数为信号量。

 如果希望在一个函数中启动线程并调用该函数,应该这样写代码

void reading(void* name);这个函数一定要是void的返回类型。然后可以在调用函数中这样写:

_beginthread(&reading,0,(void*)english); 其中第一参数是要调用函数的函数指针。第二个函数是线程优先级一般为0。第三个参数是个void指针,一般用来传函数的参数。如果想传多个参数只要把那个指针指向一个结构体就可以。到函数那里再转换为相应的结构体指针就可以了。

Sleep(5000L);这个函数一般是用来让线程睡眠的。参数是unsigned long,现在是睡5秒。
这只是多线程的编程常用到的几个函数。对于多线程编程还要注意同步和死锁,在这篇文字就不讨论了。

 

原创粉丝点击