多线程无参数
5 T8 C6 t6 u7 t9 _5 N$ n7 q// WinThread.cpp : 定义控制台应用程序的入口点。
// Windows 多线程使用
#include "stdafx.h"
using namespace std;
unsigned int ListenMusic()
{
for (int i = 0; i < 100; i++)
{
std::cout << "正在听歌" << endl;
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "正在走路" << endl;
_beginthread((void (_cdecl *)(void*))ListenMusic,0,nullptr);
for (int i = 0; i < 20; i++)
{
std::cout << "吹口哨" << endl;
}
system("pause");
return 0;
} 运行结果:
# x2 ]7 |" d4 Y' K# o
5 O4 n% h9 `" I* g& k" ^ Q
多线程有参数9 B. Q- i3 \% S' ^6 o7 |- [
// MultiThreading.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "MultiThreading.h"
using namespace std;
struct Node
{
int a;
int b;
};
void WINAPI func(Node * cur_node)
{
for (int i = 0; i < 100 ; i++)
{
cout << cur_node->a << endl;
}
cout << "测试"<< endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node * dd = new Node();
dd->a = 3;
dd->b = 2;
HANDLE hHandle =CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)func,dd,NULL,NULL);
WaitForSingleObject(hHandle,INFINITE); //等待当前线程执行结束
//CloseHandle(hHandle);
delete dd;
system("pause");
return 0;
} 运行结果:# h) W+ m7 ` k9 x3 k2 K; X- z1 n. r2 H
7 Z: ^1 s7 E$ K1 O
互斥锁使用
5 t4 \& \4 i, V! U1 ~* j// ThreadStudy.cpp : 定义控制台应用程序的入口点。
//多线程学习:可以实现异步操作
#include "stdafx.h"
using namespace std;
std::_Mutex cur_mutex;
int WINAPI run(int * n)
{
cur_mutex._Lock();
for (int i = 0; i < 5; i++)
{
cout << "thread " <<*n << endl;
}
cur_mutex._Unlock();
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
int m = 2;
int n = 3;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0,(unsigned int (__stdcall *)(void *))run, &m, 0, NULL);
HANDLE h2Thread = (HANDLE)_beginthreadex(NULL, 0,(unsigned int (__stdcall *)(void *))run, &n, 0, NULL);
system("pause");
return 0;
} 运行结果:5 N. d( ?3 z5 l \- b
|