标签:printf func2 func1 pthread int 编程 线程 Linux NULL
#include 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 #include 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 #include //需要声明此库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 #include //需要声明此库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;}
标签:printf,func2,func1,pthread,int,编程,线程,Linux,NULL 来源: https://blog.51cto.com/u_15249901/2848394
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。