zoukankan      html  css  js  c++  java
  • advacing lnux program Joining Threads[copy]

    One solution is to force mainto wait until the other two threads are done.What we
    need is a function similar to waitthat waits for a thread to finish instead of a process.
    That function is pthread_join,which takes two arguments: the thread ID of the
    thread to wait for, and a pointer to a void*variable that will receive the finished
    thread’s return value. If you don’t care about the thread return value, pass NULLas the
    second argument.

    一个解决办法是强迫main函数等待另外两个线程的结束。我们需要一个类似wait的函
    数,但是等待的是线程而不是进程。这个函数是pthread_join。它接受两个参数:线程ID,
    和一个指向void*类型变量的指针,用于接收线程的返回值。如果你对线程的返回值不感兴
    趣,则将NULL作为第二个参数。

    The moral of the story: Make sure that any data you pass to a thread by reference is
    not deallocated,even by a different thread, until you’re sure that the thread is done with
    it.This is true both for local variables, which are deallocated when they go out of
    scope, and for heap-allocated variables, which you deallocate by calling free(or using
    deletein C++).

    int main ()
    {
    pthread_t thread1_id;
    pthread_t thread2_id;
    struct char_print_parms thread1_args;
    struct char_print_parms thread2_args;

    /* Create a new thread to print 30,000 x’s. */
    thread1_args.character = ’x’;
    thread1_args.count = 30000;
    pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
    /* Create a new thread to print 20,000 o’s. */
    thread2_args.character = ’o’;
    thread2_args.count = 20000;
    pthread_create (&thread2_id, NULL, &char_print, &thread2_args);
    /* Make sure the first thread has finished. */
    pthread_join (thread1_id, NULL);
    /* Make sure the second thread has finished. */
    pthread_join (thread2_id, NULL);
    /* Now we can safely return. */
    return 0;
    }

  • 相关阅读:
    【ZJOI 2008】 生日聚会
    BZOJ2135 刷题计划(贪心+二分)
    BZOJ2124 等差子序列(树状数组+哈希)
    BZOJ2282 SDOI2011消防/NOIP2007树网的核(二分答案+树形dp)
    BZOJ1304 CQOI2009叶子的染色(树形dp)
    BZOJ1283 序列(费用流)
    BZOJ1266 AHOI2006上学路线(最短路+最小割)
    BZOJ1041 HAOI2008圆上的整点(数论)
    BZOJ3505 CQOI2014数三角形(组合数学)
    BZOJ5206 JSOI2017原力(三元环计数)
  • 原文地址:https://www.cnblogs.com/michile/p/2890681.html
Copyright © 2011-2022 走看看