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

  • 相关阅读:
    银行卡号每隔四位添加一个分隔符
    clipboard.js实现文本复制
    选中|复制文本
    react---之下拉菜单默认选中的值始终不变的问题
    create-react-app支持less配置
    数对
    安置路灯
    被三整除
    牛牛找工作
    C++ std::pair
  • 原文地址:https://www.cnblogs.com/michile/p/2890681.html
Copyright © 2020-2023  润新知