加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

多线程创建小例

发布时间:2020-12-16 07:42:22 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 学习windows下多线程的创建 使用WINAPI的CreateThread 和C/C++的_beginthread/_beginthreadex 和pthread的pthread_create win7 mingw /*purpose:练习w

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

学习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_An";
		Sleep(500);
	}
}

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

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

//使用pthread_create创建的线程函数
void* thread_D(void *param)
{
	for(int i = 0; i < 5; i++) {
		cout << "thread Dn";
		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

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读