c语言怎么创建线程和使用

Python014

c语言怎么创建线程和使用,第1张

用 pthread_t创建线程名字。然后pthread_create开辟线程。

具体使用。

比如有一个函数

void *hello()

{

printf("create pthread!\n");

}

,然后在main函数里面调用,

int main()

{

pthread_t a_thread;

pthread_create(&a_thread, NULL, (void *)hello, NULL)

}

这样就完成了hello()函数的创建和使用,接下来hello函数就会在一个线程中运行

下面为C语言调用WIN API实现创建线程:

1,导入<windows.h>头文件

2,声明实现方法DWORD WINAPI ThreadProc1( LPVOID lpParam ) {}

3,在main()方法中调用 CreateThread(NULL,0 ,ThreadProc1,NULL,0,NULL)

要注意的是主线程不能结束,如果主线程结束,则它的子线程也会被杀死。

#include <windows.h>

#include <stdio.h>

#include<time.h>

DWORD WINAPI ThreadProc1( LPVOID lpParam )

{

int i=0

time_t timer

while(1)

{

timer=time(NULL)

printf("The current time is: %s\n",asctime(localtime(&timer)))

sleep(1)

}

}

void main()

{

int i=0

//让主线程进入循环,主线程若退出,子线程1,2会被系统“杀死”

//创建线程1

CreateThread(

NULL, // default security attributes

0, // use default stack size

ThreadProc1,// thread function

NULL, // argument to thread function

0, // use default creation flags

NULL) // returns the thread identifier

for()

{

}

}

/*这是我写的最简单的多线程程序,看懂不?*/

#include <windows.h>

#include <stdio.h>

//#include <strsafe.h>

DWORD WINAPI ThreadProc1( LPVOID lpParam )

{

int i=0,j=0

while(1)

{

printf("hello,this thread 1 ...\n")

//延时

for(i=0i<200000000i++)

{

}

}

}

DWORD WINAPI ThreadProc2( LPVOID lpParam )

{

int i=0,j=0

while(1)

{

printf("hello,this thread 2 ...\n")

//延时

for(i=0i<200000000i++)

{

}

}

}

void main()

{

int i=0

//创建线程1

CreateThread(

NULL, // default security attributes

0, // use default stack size

ThreadProc1,// thread function

NULL, // argument to thread function

0, // use default creation flags

NULL) // returns the thread identifier

//创建线程2

CreateThread(

NULL, // default security attributes

0, // use default stack size

ThreadProc2,// thread function

NULL, // argument to thread function

0, // use default creation flags

NULL) // returns the thread identifier

//让主线程进入循环,主线程若退出,子线程1,2会被系统“杀死”

while(1)

{

printf("hello,this thread 0 ...\n")

//延时

for(i=0i<200000000i++)

{}

}

}