相关文件及函数说明:
<pthread.h>:这是线程头文件,与线程有关的函数和类型均在这里面定义。
pthread_t :线程标识符类型定义,在创建线程时必须要使用线程标识符。
pthread_create();线程创建函数,用于创建函数有四个参数,其中第二个和第四个置NULL就好。第一个是线程标识符,第三个是线程函数的指针,为了方便,在写线程函数时可定义函数为指针类型。
pthread_join():线程等待函数,为了防止线程还未运行结束,但是主进程结束导致的问题。有两个参数,第一个参数为要等待的进程标识符,第二个参数直接置NULL即可。
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include<windows.h>
#include<pthread.h>
pthread_t thread[2];
void *PrintNumber()
{
for(int i=0;i<50;i++){
printf("线程PrintNumber()正在执行");
printf("number=%d\n",i);
Sleep(10);
}
}
void *PrintCharacter()
{
char mych='a';
for(int j=0;j<50;j++){
printf("线程PrintCharacter()正在执行"