1 // MultiThreadTest.cpp : Defines the entry point for the console application.
2 // Thread 创建,挂起等
3
4 #include "stdafx.h"
5 #include<Windows.h>
6 #include<iostream>
7 #include<string>
8 using namespace std;
9 DWORD WINAPI myThread(LPVOID argv);//声明一个线程函数
10 int _tmain(int argc, _TCHAR* argv[])
11 {
12 string s;
13 HANDLE myHandle;
14 do{
15 cin.clear();
16 cin.sync();
17 cin>>s;
18 switch(s.at(0)){
19 case '0':
20 myHandle=CreateThread(NULL,0,myThread,(LPVOID)s.c_str(),0,NULL);//创建线程
21 break;
22 case '1':
23 if(myHandle) SuspendThread(myHandle);//挂起线程
24 break;
25 case '2':
26 if(myHandle) ResumeThread(myHandle);//回复线程
27 break;
28 case '3':
29 if(myHandle) TerminateThread(myHandle,0);//终止线程
30 break;
31 case '4':
32 if(myHandle) SetThreadPriority(myHandle,THREAD_PRIORITY_NORMAL);//设定线程优先级
33 break;
34 default:
35 break;
36 }
37 cout<< s << endl;
38 }while(s != "exit" && s != "quit");
39 return 0;
40 }
41 DWORD WINAPI myThread(LPVOID argv){
42 int i=0;
43 char buff[200];
44 ZeroMemory(buff,sizeof(buff));
45 memcpy(buff,argv,200);
46 while(++i){
47 cout<<"Extra thread executing with argument string:"<<buff<<endl;
48 Sleep(10000);
49 if(i==40) ExitThread(0);
50 }
51 }
// MultiThreadTest.cpp : Defines the entry point for the console application.
//多线程,利用全局变量传值,通信.
#include "stdafx.h"
#include<Windows.h>
#include<iostream>
#include<string>
using namespace std;
volatile int ThreadData = 0;
void ThreadProcess()
{
printf("sub thread process.\n");
for(int i = 0 ; i < 6 ; i ++)
{
ThreadData+=1000;
Sleep(1000);
printf("Sub Thread Tick %5d! %5d\n",(i+1)*1000,ThreadData);
}
printf("Exit Sub Thread!\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread;
DWORD ThreadID;
hThread=CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)ThreadProcess,
NULL,
0,
&ThreadID);
printf("main thread process\n");
for(int i = 0 ; i < 10 ; i++)
{
ThreadData-=600;
Sleep(600);
printf("Main Thread Tick %5d! %5d\n",(i+1)*600,ThreadData);
}
printf("Main Thread Loop Finished!\n");
system("pause");
return 0;
}