Thread in WIN32 & Linux

来源:互联网 发布:linux系统管理员招聘 编辑:程序博客网 时间:2024/05/18 23:25

以下是WIN32中的线程创建,主要创建函数在程序中给出说明

#include <iostream>#include <cstdlib>#include <windows.h>DWORD WINAPI FunProc(LPVOID lpParameter){int i(0);while (i++ < 1000){std::cout << " Thread running the " << i << " times" << std::endl;}return 0;}int _tmain(int argc, _TCHAR* argv[]){int j(0);//- 1 - 第一个参数是安全属性结构  //主要控制该线程句柄是否可为进程的子进程继承使用,默认使用NULL时表示不能继承;      //若想继承线程句柄,则需要设置该结构体,将结构体的bInheritHandle成员初始化为TRUE;//- 2 - cbStack表示的线程初始栈的大小,若使用0则表示采用默认大小初始化(1M);//- 3 - lpStartAddr表示线程开始的位置,即线程要执行的函数代码,这点有点类似于回调函数的使用;//- 4 - lpvThreadParam用来接收线程过程函数的参数,不需要时可以设置为NULL;//- 5 - fdwCreate表示创建线程时的标志,  //CREATE_SUSPENDED表示线程创建后挂起暂不执行,必须调用ResumeThread才可以执行,0表示线程创建之后立即执行//- 6 - lpIDThread用来保存线程的ID;HANDLE hThread_1 = CreateThread(NULL, 0, FunProc, NULL, 0, NULL);CloseHandle(hThread_1);while ( j++ < 1000){std::cout << "Main Thread is running for " << j << " times" << std::endl;}system("pause");return 0;}

以下是linux中的线程创建

#include <stdio.h>#include <pthread.h>#include <ctype.h>#include <Windows.h>void *Function_t(void* Param){pthread_t myid = pthread_self();while (1){printf("线程ID=%d \n", myid);Sleep(2000);}return NULL;}int main(){pthread_t pid;pthread_create(&pid, NULL, Function_t, NULL);while (1){printf("in father process!\n");Sleep(2000);}getchar();return 1;}


0 0