我是编程的新手所以这听起来可能听起来不太好,但是在我做了一些研究之后我明白我可以创建一个新线程,这样多个代码块可以并行运行。有人可以解释我如何创建新线程。我在Windows上使用Visual Studio。
答案 0 :(得分:3)
使用pthread_create函数我们可以创建线程。
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
pthread_t tid; pthread_t tid1; void * thrd(void * a) { printf(“thread created \ n”);
printf("%u\n",(unsigned int )tid);
}
void *thrd1(void *a)
{
printf("second thread created\n");
printf("%u\n",(unsigned int)tid1);
}
main()
{
int a=pthread_create(&tid,NULL,thrd,NULL);
int b=pthread_create(&tid1,NULL,thrd1,NULL);
sleep(1);
}
答案 1 :(得分:1)
试试那段代码
#include<stdio.h>
#include<pthread.h>
void *hello(void *arg)
{
printf("thread id=%u\n",(unsigned)pthread_self());
printf("hello welocme Thread created \n");
}
main()
{
pthread_t tid;
tid=pthread_create(&tid,NULL,hello,NULL);
}
编译:
cc filename.c -pthread