#include <stdio.h>
void func1()
{
while(1){
printf("This is func1\n");
sleep(1);
}
}
void func2()
{
while(1){
printf("This is func2\n");
sleep(1);
}
}
int main()
{
func1();
func2();
return 0;
}
上面的代码我们可以知道两个函数里面都设置了while(1)死循环,所以在主函数里面只能执行func1()函数。
要同时运行func1()与func2()就需要用到Linux线程。
线程代码例子:
#include <stdio.h>
#include <pthread.h>
void* thread( void *arg )
{
printf( "This is a thread and arg = %d.\n", *(int*)arg);
*(int*)arg = 0;
return arg;
}
int main( int argc, char *argv[] )
{
pthread_t th;
int ret;
int arg = 10;
int *thread_ret = NULL;
ret = pthread_create( &th, NULL, thread, &arg ); //第一个是线程描述符;第二个一般写NULL;第三个是线程;第四个是函数的参数
if( ret != 0 ){
printf( "Create thread error!\n");
return -1;
}
printf( "This is the main process.\n" );
pthread_join( th, (void**)&thread_ret );
printf( "thread_ret = %d.\n", *thread_ret );
return 0;
}
注意:在linux终端运行线程程序时,需要链接pthread的库,所以运行程序需要加 -lpthread
gcc **.c -lphread
所以修改原例子代码:
#include <stdio.h>
#include <pthread.h> //需要声明此库
void *func1() //需要加个*
{
while(1){
printf("This is func1\n");
sleep(1);
}
}
void func2()
{
while(1){
printf("This is func2\n");
sleep(1);
}
}
int main()
{
pthread_t, th1;
pthread_create(&th1, NULL, func1, NULL);
//func1();
func2();
return 0;
}
修改后的代码进行运行就会让两个函数同时运行。
也可创建两个线程:
#include <stdio.h>
#include <pthread.h> //需要声明此库
void *func1() //需要加个*
{
while(1){
printf("This is func1\n");
sleep(1);
}
}
void *func2()
{
while(1){
printf("This is func2\n");
sleep(1);
}
}
int main()
{
pthread_t, th1;
pthread_t, th2;
pthread_create(&th1, NULL, func1, NULL); //第二个线程
phtread_create(&th2, NULL, func2, NULL); //第三个线程
//func1();
//func2();
while(1); //主线程
return 0;
}