1.一个多线程程序
新建一个win32 console application,取名:MultiThread,选空的工程,并建立一个名为MultiThread的源文件编辑:
#include
#include
#include
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
int index=0;
void main()
{
HANDLE hThread1;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
CloseHandle(hThread1);
while(index++<1000)
cout<<"main thread is running"< //Sleep(10);//让主线程暂停运行10毫秒
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
while(index++<1000)
cout<<"thread1 is running"< return 0;
}
2.模拟火车站的售票系统
#include
#include
#include
DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
int index=0;
int tickets=100;//指定的票数
HANDLE hMutex;//定义一个互斥对象句柄
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
// while(index++<1000)
// cout<<"main thread is running"<
//Sleep(10);//让主线程暂停运行10毫秒
//hMutex=CreateMutex(NULL,FALSE,NULL);//创建一个匿名的互斥对象,FALSE指定主线程不拥有互斥对象
//hMutex=CreateMutex(NULL,TRUE,NULL);//创建互斥对象时,就把这个对象分配给了主线程,并把线程ID也设置成了1
hMutex=CreateMutex(NULL,TRUE,"tickets");
if(hMutex) //利用命名互斥的特性,可以使应用程序只能打开一个实例
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only instance can run!"< return ;
}
}
WaitForSingleObject(hMutex,INFINITE);//主线程再次请求互斥对象,此时线程ID变成2
ReleaseMutex(hMutex);
//释放互斥对象,线程ID减1后,变成1,互斥对象仍然没有变为已通知状态,仍然属于主线性,所以子线程没有机会执行
ReleaseMutex(hMutex);
//再次释放互斥对象,线程ID再减1,变成0,互斥对象变为已通知状态,此时子线程可以调用这个互斥对象
//保证在两个子线程卖完100张票之前不能退出
Sleep(4000);//让主线程睡眠4秒钟,此时主线程不占用CPU的执行时间,处于等待状态
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
//while(index++<1000)
// cout<<"thread1 is running"<
/* while(TRUE) //不断的销售火车票
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
//ININITE指定在等待的互斥对象变为有信号之前一直等待
if(tickets>0)
{
//Sleep(1);//在未添加互斥对象时,睡眠使它进入另一个线程
cout<<"thread1 sell ticket:"<
}
else
break;
ReleaseMutex(hMutex);//释放互斥对象
}
*/
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread1 is running !"< //线程终止后,操作系统会自动将互斥对旬的引用计数和线程ID设为0
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
/* while(TRUE) //不断的销售火车票
{
//ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
//ININITE指定在等待的互斥对象变为有信号之前一直等待
if(tickets>0)
{
//Sleep(1);
//在未添加互斥对象时,睡眠使它进入另一个线程,这样出现了卖出第0张票
cout<<"thread2 sell ticket:"<
}
else
break;
ReleaseMutex(hMutex);//释放互斥对象
}
*/
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread1 is running !"< return 0;
}
3.多线程实现网络聊天室程序
编写接收端:
新建一个MFC的基于对话框的应用程序,取名为Chat,再编辑对话框资源,如图:
在CChatApp::InitInstance()函数中编辑:
BOOL CChatApp::InitInstance()
{
if(!AfxsocketInit())//加载套接字
{
AfxMessageBox("加载套接字失败!");
return FALSE;
}
AfxEnableControlContainer();
..........
..........
并在头文件stdafx.h预编译后边,添加头文件:
#include //包含要用到的套接字函数的头文件
再在CChatDlg类上添加一个私有成员变量:
SOCKET m_socket;
和一个成员函数BOOL CChatDlg::InitSocket(),编辑:
BOOL CChatDlg::InitSocket()
{
m_socket=socket(AF_INET,SOCK_DGRAM,0);//创建数据报套接字
if(INVALID_SOCKET==m_socket)//判断套接字是否创建成功
{
MessageBox("套接字创建失败!");
return FALSE;
}
SOCKADDR_IN addrSock;
addrSock.sin_family=AF_INET;
addrSock.sin_port=htons(6000);
addrSock.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
int retval;
retval=bind(m_socket,(SOCKADDR*)&addrSock,sizeof(SOCKADDR));
if(SOCKET_ERROR==retval)
{
closesocket(m_socket);
MessageBox("绑定失败!");
return FASLE;
}
return TRUE;
}
并在CChatDlg::OnInitDialog()中添加:
BOOL CChatDlg::OnInitDialog()
{
..........
..........
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
InitSocket();//初始化套接字
RECVPARAM *pRecvParam=new RECVPARAM;//new一个结构体指针
pRecvParam->sock=m_socket;
pRecvParam->hwnd=m_hWnd;//给结构体的成员初始化
HANDLE hThread=CreateThread(NULL,0,RecvProc,(LPVOID)pRecvParam,0,NULL);//创建一个线程
CloseHandle(hThread);//关闭线程句柄
return TRUE; // return TRUE unless you set the focus to a control }
在ChatDlg.h中添加一个结构体:
struct RECVPARAM
{
SOCKET sock;
HWND hwnd;
};
并在CChatDlg添加一个静态的成员函数:
public:
static DWORD WINAPI RecvProc(LPVOID lpParameter);
并在ChatDlg.cpp编辑:
DWORD WINAPI CChatDlg::RecvProc(LPVOID lpParameter)//线程函数
{
SOCKET sock=((RECVPARAM*)lpParameter)->sock;//套接字
HWND hwnd=((RECVPARAM*)lpParameter)->hwnd;//对话框句柄
SOCKADDR_IN addrFrom;
int len=sizeof(SOCKADDR);
char recvBuf[200];
char tempBuf[300];
int retval;
while(TRUE)
{
retval=recvfrom(sock,recvBuf,200,0,(SOCKADDR*)&addrFrom,&len);
if(SOCKET_ERROR==retval)
break;
sprintf(tempBuf,"%s说:%s",inet_ntoa(addrFrom.sin_addr),recvBuf);
::PostMessage(hwnd,WM_RECVDATA,0,(LPARAM)tempBuf);//将接收到字符传递到对话框句柄
}
return 0;
}
在ChatDlg.h中
#define WM_RECVDATA WM_USER+1 //定义消息
..........
..........
// Generated message map functions
//{{AFX_MSG(CChatDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
//}}AFX_MSG
afx_msg void OnRecvData(WPARAM wParam,LPARAM lParam);//消息响应函数原型声明
DECLARE_MESSAGE_MAP()
并在ChatDlg.cpp中添加消息映射:
BEGIN_MESSAGE_MAP(CChatDlg, CDialog)
//{{AFX_MSG_MAP(CChatDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_MESSAGE(WM_RECVDATA,OnRecvData) //消息映射
END_MESSAGE_MAP()
在ChatDlg.cpp中添加函数CChatDlg::OnRecvData(WPARAM wParam,LPARAM lParam):
void CChatDlg::OnRecvData(WPARAM wParam,LPARAM lParam)//消息响应函数的实现
{
CString str=(char*)lParam;//取出由消息传来的数据
CString strTemp;
GetDlgItemText(IDC_EDIT_RECV,strTemp);//将接收编辑框中的文本存到strTemp中
str+="/r/n";
str+=strTemp;//加上先前的数据
SetDlgItemText(IDC_EDIT_RECV,str);//将数据设置到编辑框
}
运行,OK !
编写发送端:
双击发送按钮,生成消息响应函数,编辑:
void CChatDlg::OnBtnSend() //发送按钮消息响应函数
{
// TODO: Add your control notification handler code here
DWORD dwIP;
((CIPAddressCtrl*)GetDlgItem(IDC_IPADDRESS1))->GetAddress(dwIP);//得到IP控制中的IP地址
SOCKADDR_IN addrTo;
addrTo.sin_family=AF_INET;
addrTo.sin_port=htons(6000);
addrTo.sin_addr.S_un.S_addr=htonl(dwIP);
CString strSend;
GetDlgItemText(IDC_EDIT_SEND,strSend);//将发送编辑框控件中的数据存到strSend中
sendto(m_socket,strSend,strSend.GetLength()+1,0,
(SOCKADDR*)&addrTo,sizeof(SOCKADDR));//发送套接字
SetDlgItemText(IDC_EDIT_SEND,"");
}
让接收编辑框支持多行文本,将IDC_EDIT_RECV编辑框的多行属性选中即可,运行,OK!
--------------------------------------------------------------------------------
CreateThread
The CreateThread function creates a thread to execute within the virtual address space of the calling process.
To create a thread that runs in the virtual address space of another process, use the CreateRemoteThread function.
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
SIZE_T dwStackSize, // initial stack size
LPTHREAD_START_ROUTINE lpStartAddress, // thread function
LPVOID lpParameter, // thread argument
DWORD dwCreationFlags, // creation option
LPDWORD lpThreadId // thread identifier
);
Parameters
lpThreadAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.
Windows NT/2000/XP: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor.
dwStackSize
[in] Specifies the initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable. For more information, see Thread Stack Size.
lpStartAddress
[in] Pointer to the application-defined function of type LPTHREAD_START_ROUTINE to be executed by the thread and represents the starting address of the thread. For more information on the thread function, see ThreadProc.
lpParameter
[in] Specifies a single parameter value passed to the thread.
dwCreationFlags
[in] Specifies additional flags that control the creation of the thread. If the CREATE_SUSPENDED flag is specified, the thread is created in a suspended state, and will not run until the ResumeThread function is called. If this value is zero, the thread runs immediately after creation. At this time, no other values are supported.
Windows XP: If the STACK_SIZE_PARAM_IS_A_RESERVATION flag is specified, the dwStackSize parameter specifies the initial reserve size of the stack. Otherwise, dwStackSize specifies the commit size.
lpThreadId
[out] Pointer to a variable that receives the thread identifier.
Windows NT/2000/XP: If this parameter is NULL, the thread identifier is not returned.
Windows 95/98/Me: This parameter may not be NULL.
Return Values
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Note that CreateThread may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread's process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).
Windows 95/98/Me: CreateThread succeeds only when it is called in the context of a 32-bit program. A 32-bit DLL cannot create an additional thread when that DLL is being called by a 16-bit program.
Remarks
The number of threads a process can create is limited by the available virtual memory. By default, every thread has one megabyte of stack space. Therefore, you can create at most 2028 threads. If you reduce the default stack size, you can create more threads. However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread would process all requests in a queue before processing requests in the next queue.
The new thread handle is created with THREAD_ALL_ACCESS to the new thread. If a security descriptor is not provided, the handle can be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread. If the thread impersonates a client, then calls CreateThread with a NULL security descriptor, the thread object created has a default security descriptor which allows access only to the impersonation token's TokenDefaultDacl owner or members. For more information, see Thread Security and Access Rights.
The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread's return value.
The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.
When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.
The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.
The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:
A thread that uses functions from the C run-time libraries should use the beginthread and endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.
Example Code
For an example, see Creating Threads.
Requirements
Windows NT/2000/XP: Included in Windows NT 3.1 and later.
Windows 95/98/Me: Included in Windows 95 and later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.