c语言windows下写多线程的问题

来源:百度知道 编辑:UC知道 时间:2024/05/19 10:55:32
以下是我的测试代码:
#include <process.h>
#include <stdio.h>
#include <windows.h>
void thread_proc(void *arg)
{
printf("I am thread %d,my id is:",arg);
_endthread();
}
int main()
{
unsigned pid;
int count=0;

while(count<5)
{
_beginthreadex(NULL,0, (unsigned (__stdcall *) (void *))thread_proc,(void *)count,0,&pid);
Sleep( 10);
printf("%d\n",pid);
count++;
}
return 0;
}
我的问题是:
倘若没有Sleep(10)的时候,打印结果如下:

1776
204
3840
I am thread 0,my id is:I am thread 1,my id is:I am thread 2,my id is:3104
3528
请按任意键继续. . .

而有Sleep(10)的时候,打印结果如下:

I am thread 0,my id is:3544
I am thread 1,my id is:256
I am thread 2,my id is:1728
I am thread 3,my id is:2824
I am thread 4,my id is:2620
请按任意键继续. . .

这是怎么回事呢?难道与线程间同步与互斥有关???

因为你没有加同步互斥机制,所以如果没有足够的sleep的话,线程函数和main函数里的printf("%d\n",pid);之间的顺序是未知的,视你的系统环境而定。比如我运行了几次,结果都不一样,有时候是只输出5个随机数,有时候和你的结果一样。如果加了足够的sleep,那么就可以确保在执行printf("%d\n",pid);
前,线程函数已经结束了,那么就不会出现混乱的结果了。

printf("I am thread %d,my id is:",arg);

难道不是 printf("I am thread %d,my id is:",*arg);

unsigned pid;

与操作系统的调度有关,举一个最简单的例子,比如说调度时间限是1000,而开始_beginthreadex时还剩800,_beginthreadex用掉200还剩600,因为被创建线程调度优先级与创建线程相同,所以这时还是创建线程在执行(未发生调度),printf函数较快用掉50,还剩550,按这种规律发展的话时限是:800,600,(打印pid),550,350,(打印pid),300,100,(打印pid), 50,0,为0时主线程在_beginthreadex中,这时发生调度执行另外一线程才打印了i am thread。 而Sleep是告诉系统进入等待主动放弃了时限,所以立即调度其他线程。本例中数字是虚数,只表示了相对大小。