POSIX之Thread Barrier

2022-06-30 19:02:30 浏览数 (1)

VxWorks7支持了Posix的Thread Barrier,用于多线程的同步

代码语言:javascript复制
typedef struct
    {
    int barrierAttrStatus;  /* PTHREAD_INITIALIZED_OBJ | PTHREAD_DESTROYED_OBJ */
    int barrierAttrPshared; /* PTHREAD_PROCESS_PRIVATE | PTHREAD_PROCESS_SHARED */
    } pthread_barrierattr_t;
int pthread_barrierattr_init
    (
    pthread_barrierattr_t *pAttr
    );
int pthread_barrierattr_destroy
    (
    pthread_barrierattr_t *pAttr
    );

int pthread_barrierattr_getpshared
    (
    const pthread_barrierattr_t *attr,
    int *pshared
    );
int pthread_barrierattr_setpshared
    (
    pthread_barrierattr_t *attr,
    int pshared
    );

int pthread_barrier_init
    (
    pthread_barrier_t *pBarrier,
    const pthread_barrierattr_t *pAttr,
    unsigned count
    );
int pthread_barrier_destroy
    (
    pthread_barrier_t *pBarrier
    );
int pthread_barrier_wait
    (
    pthread_barrier_t *pBarrier
    );

直接跑个例子

代码语言:javascript复制
/*
 * 版权所有  公众号  VxWorks567
 */
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

static void *doWork(void *pMyBarrier)
{
    printf("thread %s, line %dn", taskName(0), __LINE__);
    pthread_barrier_wait(pMyBarrier);
    printf("thread %s, line %dn", taskName(0), __LINE__);

    pthread_exit(NULL);
    return NULL;
    }

void testPosixBarrier()
{
    pthread_t thread1;
    pthread_t thread2;
    pthread_t thread3;
    pthread_barrier_t myBarrier;
    int ret;

    sleep(1);

    /* Turn this task into a POSIX thread */
    pthread_self();

    /* Initializes the barrier "myBarrier" to wait for three threads. */
    pthread_barrier_init(&myBarrier, NULL, 3 1);

    printf("thread %s, line %dn", taskName(0), __LINE__);

    /* Create three threads. */
    ret = pthread_create(&thread1, NULL, &doWork, (void *)&myBarrier);
    sleep(1);
    ret = pthread_create(&thread2 ,NULL, &doWork, (void *)&myBarrier);
    sleep(1);
    ret = pthread_create(&thread3, NULL, &doWork, (void *)&myBarrier);

    printf("thread %s, line %dn", taskName(0), __LINE__);
    pthread_barrier_wait(&myBarrier);
    printf("thread %s, line %dn", taskName(0), __LINE__);

    pthread_barrier_destroy(&myBarrier);
    pthread_exit((void *)OK);
    }

主线程依次启动三个线程,必须四个线程都执行到pthread_barrier_wait()后,后续的pthread_barrier_destroy()才会执行

这个场景是不是似曾相识,没错,多任务同步!Thread Barrier的底层就是用Task的Binary Semaphore封装的

0 人点赞