apue- thread 線程學(xué)習(xí)(pthread_join,barrier,mutex)

0x01 等待子線程返回結(jié)果

pthread_join 會阻塞當前線程, 直到子線程返回結(jié)果

#include "apue.h"
#include <pthread.h>

void *sub(void *arg) {
    printf("sub-thread-start ....\n");
    sleep(2);
    printf("sub-thread-end ....\n");
    pthread_exit((void *) 180);
}


int main(int argc, char *argv[]) {
    pthread_t p;
    void *rst;
    printf("main thread start ...\n");

    int e = pthread_create(&p, NULL, sub, NULL);
    if (e != 0)
        err_exit(e, "can't create thread");

    // main thread wait until get result from sub thread
    e = pthread_join(p, &rst);
    if (e != 0)
        err_exit(e, "can't joint thread");

    printf("main thread done %lu \n", (long)rst);
    exit(0);
}

  • 運行結(jié)果:
main thread start ...
sub-thread-start ....
sub-thread-end ....
main thread done 180 

0x02 mutex 上鎖超時


#include "apue.h"
#include <pthread.h>

int main(int argc, char *argv[]) {
    int e;
    struct timespec tout;
    struct tm *tmp;
    char buf[64];
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_lock(&lock);
    printf("mutex is locked\n");

    clock_gettime(CLOCK_REALTIME, &tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf, sizeof(buf), "%r", tmp);
    printf("current time is %s\n", buf);

    tout.tv_sec += 5;

    // lock a mutex with timeout
    e = pthread_mutex_timedlock(&lock, &tout);
    clock_gettime(CLOCK_REALTIME, &tout);
    tmp = localtime(&tout.tv_sec);
    strftime(buf, sizeof(buf), "%r", tmp);
    printf("the time is now %s \n", buf);

    if (e == 0)
        printf("mutex locked again!\n");
    else
        printf("can't lock mutex again: %s\n", strerror(e));

    exit(0);
}
  • 輸出結(jié)果:
mutex is locked
current time is 10:38:44 AM
the time is now 10:38:49 AM 
can't lock mutex again: Connection timed out

0x03 線程組同步 barrier

  • 啟用一個barrier并指定線程數(shù) : pthread_barrier_init(&b, NULL, TASK_CNT + 1);
  • 每一個線程都會執(zhí)行并等待到: pthread_barrier_wait(&b);
    當所有線程都到達這里后, 才都向后繼續(xù)執(zhí)行.
#include "apue.h"
#include <pthread.h>
#include <sys/time.h>


#define TASK_CNT ((unsigned int)5)

pthread_barrier_t b;

void *sub(void *arg) {
    printf("[%lu]thread running within : %lu seconds\n", pthread_self(), (long) arg);
    sleep((long) arg);
    printf("[%lu]thread done\n", pthread_self());
    pthread_barrier_wait(&b);
    pthread_exit((void *) 0);
}


int main(int argc, char *argv[]) {
    struct timeval start, end;
    long long startusec, endusec;
    double elapsed;
    int err;
    pthread_t tid;

    gettimeofday(&start, NULL);
    pthread_barrier_init(&b, NULL, TASK_CNT + 1);
    srandom(1);

    for (int i = 0; i < TASK_CNT; ++i) {
        err = pthread_create(&tid, NULL, sub, (void *) (random() % 10));
        if (err != 0)
            err_exit(err, "can't create thread");
    }
    pthread_barrier_wait(&b);

    gettimeofday(&end, NULL);
    startusec = start.tv_sec * 1000000 + start.tv_usec;
    endusec = end.tv_sec * 1000000 + end.tv_usec;
    elapsed = (double) (endusec - startusec) / 1000000.0;
    printf("all task took %.4f seconds\n", elapsed);

    exit(0);
}
  • 結(jié)果:
[140526034429696]thread running within : 3 seconds
[140526017644288]thread running within : 7 seconds
[140526026036992]thread running within : 6 seconds
[140526009251584]thread running within : 5 seconds
[140526000858880]thread running within : 3 seconds
[140526034429696]thread done
[140526000858880]thread done
[140526009251584]thread done
[140526026036992]thread done
[140526017644288]thread done
sort took 7.0024 seconds
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市卧斟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌憎茂,老刑警劉巖珍语,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異竖幔,居然都是意外死亡板乙,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門拳氢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來募逞,“玉大人,你說我怎么就攤上這事馋评》沤樱” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵留特,是天一觀的道長纠脾。 經(jīng)常有香客問我,道長蜕青,這世上最難降的妖魔是什么苟蹈? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮右核,結(jié)果婚禮上慧脱,老公的妹妹穿的比我還像新娘。我一直安慰自己贺喝,他們只是感情好菱鸥,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布宗兼。 她就那樣靜靜地躺著,像睡著了一般采缚。 火紅的嫁衣襯著肌膚如雪针炉。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天扳抽,我揣著相機與錄音篡帕,去河邊找鬼。 笑死贸呢,一個胖子當著我的面吹牛镰烧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播楞陷,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼怔鳖,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了固蛾?” 一聲冷哼從身側(cè)響起结执,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎艾凯,沒想到半個月后献幔,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡趾诗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年蜡感,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片恃泪。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡郑兴,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出贝乎,到底是詐尸還是另有隱情情连,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布览效,位于F島的核電站蒙具,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏朽肥。R本人自食惡果不足惜禁筏,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望衡招。 院中可真熱鬧篱昔,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至穗椅,卻和暖如春辨绊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背匹表。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工门坷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人袍镀。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓默蚌,卻偏偏與公主長得像,于是被迫代替她去往敵國和親苇羡。 傳聞我的和親對象是個殘疾皇子绸吸,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353