前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POSIX之Thread Barrier

POSIX之Thread Barrier

作者头像
Taishan3721
发布2022-06-30 19:02:30
5450
发布2022-06-30 19:02:30
举报
文章被收录于专栏:这里只有VxWorks

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 %d\n", taskName(0), __LINE__);
    pthread_barrier_wait(pMyBarrier);
    printf("thread %s, line %d\n", 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 %d\n", 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 %d\n", taskName(0), __LINE__);
    pthread_barrier_wait(&myBarrier);
    printf("thread %s, line %d\n", taskName(0), __LINE__);

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

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 这里只有VxWorks 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档