#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
void thread1(void)
{
int i=0;
for(i=0;i<6;i++)
{
printf("This is a pthread1.\n");
if(i==2)
pthread_exit(0);
sleep(1);
}
}
void thread2(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread2.\n");
pthread_exit(0);
}
int main(void)
{
pthread_t id1,id2;
//int i,ret;
int ret;
ret=pthread_create(&id1,NULL,(void *) thread1,NULL);//(void *) thread1//函数传递事,传过去的就地址
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
ret=pthread_create(&id2,NULL,(void *) thread2,NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
exit (0);
}
多线程程序示例
本文展示了一个使用pthread库创建两个并行线程的C语言程序实例。其中一个线程会在循环中打印消息直到特定条件触发退出,另一个线程则简单地执行几次打印后退出。
3010

被折叠的 条评论
为什么被折叠?



