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;
    }

  • 相关阅读:
    POJ 2240 Arbitrage spfa 判正环
    POJ 3259 Wormholes spfa 判负环
    POJ1680 Currency Exchange SPFA判正环
    HDU5649 DZY Loves Sorting 线段树
    HDU 5648 DZY Loves Math 暴力打表
    HDU5647 DZY Loves Connecting 树形DP
    CDOJ 1071 秋实大哥下棋 线段树
    HDU5046 Airport dancing links 重复覆盖+二分
    HDU 3335 Divisibility dancing links 重复覆盖
    FZU1686 神龙的难题 dancing links 重复覆盖
  • 原文地址:https://www.cnblogs.com/michile/p/2890681.html
Copyright © 2011-2022 走看看