【发布时间】:2016-04-20 08:19:53
【问题描述】:
考虑下一段代码:
#include <iostream>
#include <pthread.h>
#include <string.h>
using namespace std;
pthread_t tid[3];
void* printMe(void* arg)
{
pthread_t id = pthread_self();
if(pthread_equal(id,tid[0]))
{
cout << "first thread's in function" << endl;
}
if(pthread_equal(id,tid[1]))
{
cout << "second thread's in function" << endl;
}
if(pthread_equal(id,tid[2]))
{
cout << "third thread's in function" << endl;
}
}
int main() {
int i = 0;
int err;
while (i < 3)
{
err = pthread_create(&(tid[i]), NULL, printMe, NULL);
if (err != 0)
{
cout << "failed to create thread number " << i << strerror(i) << endl;
}
else
{
cout << "main() : creating thread number " << i << endl;
}
i++;
}
return 0;
}
我不明白线程什么时候调用他的函数? 这是正确的,因为它是创建的? (同时,主线程继续创建其他线程?)
此外,我不明白输出 -
main() : creating thread number 0
main() : creating thread number 1
main() : creating thread number 2
first thread's in function
first thread's in function
第一个线程调用了他的函数两次,而其他线程都没有调用它们的函数。
然后,我再次编译得到 -
main() : creating thread number 0
first thread's in function
main() : creating thread number 1
second thread's in function
main() : creating thread number 2
再说一遍,第三个线程呢?
为什么“有时”线程不能调用它们的函数?
【问题讨论】:
标签: c++ multithreading