这是我的第一个 pthread 程序,我不知道为什么 printf 语句在子线程中打印两次:
int x = 1;
void *func(void *p)
{
x = x + 1;
printf("tid %ld: x is %d\n", pthread_self(), x);
return NULL;
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, func, NULL);
printf("main thread: %ld\n", pthread_self());
func(NULL);
}
在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU/Linux):
1.
main thread: 140144423188224
tid 140144423188224: x is 2
2.
main thread: 140144423188224
tid 140144423188224: x is 3
3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is 3
4.
main thread: 139923881056000
tid 139923881056000: x is 3
tid 139923872798464tid 139923872798464: x is 2
3、子线程的两条输出线
对于4,同3,甚至输出都是交错的。
最佳答案
线程化通常通过时分复用发生。处理器在两个线程之间平均切换通常是低效的,因为这需要更多的努力和更高的上下文切换。通常,您会发现一个线程在切换之前会执行多次(如示例 3 和示例 4 的情况。子线程在最终终止之前执行不止一次(因为主线程退出)。
Example 2: I don't know why x is increased by the child thread while there is no output.
考虑一下。主线程执行。它调用 pthread 并创建一个新线程。新的子线程增加 x。在子线程能够完成 printf 语句之前,主线程开始执行。突然它也增加了 x。然而,主线程也能够运行 printf 语句。突然 x 现在等于 3。
主线程现在终止(也导致子线程 3 退出)。
这可能是您的案例中发生的情况,例如 2。
示例 3 清楚地表明,由于低效锁定和堆栈数据损坏,变量 x 已损坏!!
有关线程是什么的更多信息。
Link 1 - Additional info about threading
Link 2 - Additional info about threading
此外,您会发现,因为您使用的是 x 的全局变量,所以线程之间共享对该变量的访问。这很糟糕.. 非常非常糟糕,因为访问同一变量的线程会因变量 x 的同一寄存器上发生多次读写而产生竞争条件和数据损坏。
正是由于这个原因,互斥体被使用,它本质上在变量被更新时创建一个锁,以防止多个线程试图同时修改同一个变量。
互斥锁将确保 x 按顺序更新,而不是像您的情况那样偶尔更新。
有关 Pthreads in General 和 Mutex 锁定示例的更多信息,请参阅此链接。
Pthreads and Mutex variables
干杯,
彼得
关于pthreads - 线程 : one printf statement get printed twice in child thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550662/