写了一段测试代码如下:
void test001()
{
int i,j,k;
for(i=0;i<5;i++)
{
printf("This is thread run all!!!!!\n");
for(j=0;j<5000;j++)
{
for(k=0;k<1000;k++)
;
}
}
printf("This is thread 2!!!!!\n");
pthread_exit(0);
usleep(1000*500);
}
void test002()
{
printf("\nThis is thread 1!!!!!\n");
pthread_exit(0);
usleep(1000);
}
int main(int argc, char **argv)
{
int result0;
pthread_t thread1, thread2;
result0=0;
while(1)
{
result0=pthread_create(&thread1, NULL, (void *)test002,NULL);
if(result0!=0)
{
perror("pthread_create: task1.\n");
exit(0);;
}
result0=pthread_create(&thread2, NULL, (void *)test001,NULL);
if(result1!=0)
{
perror("pthread_create: task2.\n");
exit(0);
}
pthread_join(thread2, NULL);
pthread_join(thread1, NULL);
}
return 0;
}
运行结果如下:
This is thread 1!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread 2!!!!!
This is thread 1!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread 2!!!!!
This is thread 1!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
This is thread run all!!!!!
从以上的结果看,好像是一个线程运行结束后下一个线程才会运行!!没有达到分时切换运行的效果!!不知是何原因,望大家不吝赐教,谢谢了!!!
lolo.tmp 于 2010-02-13 01:28:06发表:
从上面的打印效果看,两个线程在同时运行啊,打印是穿插的,楼主你的研究结果是什么阿?
js001sdx 于 2010-02-08 15:13:50发表:
等了两天没人回答!!最终还是自己解决了!!