了解POSIX屏障机制 [英] Understanding posix barrier mechanism
问题描述
下面是一块(非常简化,用全局变量的等气味)C code,它使用POSIX屏障原语sincronize线程启动的。
Here is piece (very simplified, with global var's and other "smells") of C code, which uses posix barrier primitive to sincronize thread start.
#include <pthread.h>
#include <stdio.h>
pthread_barrier_t barrier;
void* thread_func(void* aArgs)
{
pthread_barrier_wait(&barrier);
printf("Entering thread %p\n", (void*)pthread_self());
int i;
for(i = 0 ; i < 5; i++)
printf("val is %d in thread %p \n", i, (void*)pthread_self());
}
int main()
{
pthread_t thread_1, thread_2;
pthread_barrier_init(&barrier, NULL, 2);
pthread_create(&thread_1, NULL, (void*)thread_func, NULL);
printf("Thread %p created\n", (void*)thread_1);
usleep(500);
pthread_create(&thread_2, NULL, (void*)thread_func, NULL);
printf("Thread %p created\n", (void*)thread_2);
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
pthread_barrier_destroy(&barrier);
return 0;
}
我不明白,为什么输入线......字符串同时发生不输出?当我在上面运行PROGRAMM,通常会得到一样的输出:
I can't understand, why "Entering thread ..." string occurs not simultaneously in the output? When i run above programm, usually get alike output:
Thread 0xb74fdb40 created
Thread 0xb6cfcb40 created
Entering thread 0xb6cfcb40
val is 0 in thread 0xb6cfcb40
val is 1 in thread 0xb6cfcb40
val is 2 in thread 0xb6cfcb40
val is 3 in thread 0xb6cfcb40
val is 4 in thread 0xb6cfcb40
Entering thread 0xb74fdb40
val is 0 in thread 0xb74fdb40
val is 1 in thread 0xb74fdb40
val is 2 in thread 0xb74fdb40
val is 3 in thread 0xb74fdb40
val is 4 in thread 0xb74fdb40
我有什么期望,同时启动两个线程,而出现的输入线......在输出序列串。
与编译:gcc的barrier.c -pthread
What i expect, is simultaneously starting of two threads, and appearing of "Entering thread ..." strings in sequence in the output. Compile it with: gcc barrier.c -pthread
我在做什么错呢?
推荐答案
你的障碍正在做的是preventing线程1从创建线程2之前任何输出。
What your barrier is doing is preventing Thread 1 from producing any output before Thread 2 is created.
创建两个线程后,两个越过障碍和畅通。 之后,你是不是主张任何控制至于他们是如何交织的所以线程1偶然得到它的时间片,并产生所有的输出;然后线程2获得其时间片并产生所有的输出。
After both threads are created, both cross the barrier and are unblocked. After that you are not asserting any control as to how they are interleaved. So, thread 1 happens to get its time slice and produces all its output; then thread 2 gets its time slice and produces all its output.
尝试移动屏障的之后的输入输出到更好地理解。
Try moving the barrier after the "Enter" output to get a better understanding.
这篇关于了解POSIX屏障机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!