多线程创建小例

前端之家收集整理的这篇文章主要介绍了多线程创建小例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

学习windows下多线程的创建
使用WINAPI的CreateThread
和C/C++的_beginthread/_beginthreadex
和pthread的pthread_create
win7
mingw
/*
purpose:
	练习windowAPI的线程函数CreateThread,
	和标准C库的线程函数_beginthread/_beginthreadex,和mingw的线程函数pthread_create
author:[email protected]
date:2016/4/20
*/

#include <windows.h>
#include <process.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <pthread.h> //需要-lpthread

using namespace std;

//使用_beginthread创建的线程函数,对线程控制较弱,使用_endthread(void)结束线程
void __cdecl threadA(void *p)
{
	for(int i = 0; i < 5; i++) {
		cout << "thread_A\n";
		Sleep(500);
	}
}

//使用_beginthreadex创建的线程函数
unsigned int __stdcall threadB(void *p)
{
	for(int i = 0; i < 5; i++) {
		cout << "thread B\n";
		Sleep(500);
	}
}

//使用WinAPI的CreateThread创建的线程函数
DWORD WINAPI ThreadC(LPVOID param)
{
	for(int i = 0; i < 5; i++) {
		cout << "thread C\n";
		Sleep(300);
	}
	return 0;
}

//使用pthread_create创建的线程函数
void* thread_D(void *param)
{
	for(int i = 0; i < 5; i++) {
		cout << "thread D\n";
		Sleep(400);
	}
	return 0;
}

int main(int argc,char *argv[])
{
	_beginthread(&threadA,0);
	HANDLE hEx = (HANDLE)_beginthreadex(0,&threadB,0);

	HANDLE hThread = CreateThread(0,ThreadC,0);

	pthread_t pid;
	pthread_create(&pid,thread_D,0);

	WaitForSingleObject(hThread,INFINITE);
	CloseHandle(hThread);

	WaitForSingleObject(hEx,INFINITE);
	CloseHandle(hEx);

	
	pthread_join(pid,0); //等待thread_D执行完成

	system("pause");
	return 0;
}
NAME = multi_thread_create

$(NAME): $(NAME).o 
	g++ -g -o $(NAME) $(NAME).o -lpthread -luser32 -lkernel32

$(NAME).o: $(NAME).cpp
	g++ -g -c $(NAME).cpp
make -f makefile.txt
cmd

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的C&C++相关文章