【问题标题】:pthreads running in reverse order [duplicate]pthreads以相反的顺序运行[重复]
【发布时间】:2019-01-01 20:13:17
【问题描述】:

我有这个非常简单的代码:

void *myfunc (void *variable);

int main(int argc, char *argv[])
{
    pthread_t thread1, thread2;
    char *msg1 = "First thread";
    char *msg2 = "Second thread";
    int ret1, ret2;

    ret1 = pthread_create(&thread1, NULL, myfunc, (void *) msg1);
    ret2 = pthread_create(&thread2, NULL, myfunc, (void *) msg2);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    printf("First thread ret1 = %d\n", ret1);
    printf("Second thread ret2 = %d\n", ret2);
    return 0;
}

void *myfunc (void *variable)
{
    char *msg;
    msg = (char *) variable;
    printf("%s\n", msg);
}

这是我一直得到的结果:

Second thread 
First thread
First thread ret1 = 0
Second thread ret2 = 0

在我之前创建的第一个线程的代码中,但第二个线程似乎运行第一个线程。据我所知,您无法控制哪个线程首先运行,但我已经多次运行程序,使用“for”循环,结果总是相同,看起来并不随机。有什么方法可以确保我创建的第一个线程首先运行?

【问题讨论】:

  • 线程彼此独立运行。创建它们后,您将无法控制它们的启动顺序或运行方式。如果您需要线程以特定顺序运行,则需要使用同步原语(如条件变量或信号量等)明确指定该顺序。
  • 另外,ret1ret2 变量仅包含 pthread_create 调用的成功/失败,而不是线程“返回”的内容
  • 也许还要想想“任意”、“不可预测”、“随机”和“依赖于实现”的区别。无论如何,最终,您根本不能依赖任何特定的行为。

标签: c linux posix


【解决方案1】:

有什么方法可以确保我创建的线程第一次运行 第一个?

当然有。在第一个线程之后序列化其他线程,例如使用信号量(省略错误检查):

#include <pthread.h>

#include <stdio.h>
#include <semaphore.h>
sem_t semaphore;
void *myfunc (void *variable)
{
    char *msg;
    msg = variable;
    /*if not first, wait on the semaphore and the post to it
      otherwise just post so the other threads may start*/
    if('F'!=*msg) 
        sem_wait(&semaphore);
    printf("%s\n", msg);
    sem_post(&semaphore);
}

int main(int argc, char *argv[])
{
    pthread_t thread1, thread2;
    char *msg1 = "First thread";
    char *msg2 = "Second thread";
    int ret1, ret2;

    sem_init(&semaphore,0,0);

    ret1 = pthread_create(&thread1, NULL, myfunc, (void *) msg1);
    ret2 = pthread_create(&thread2, NULL, myfunc, (void *) msg2);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    printf("First thread ret1 = %d\n", ret1);
    printf("Second thread ret2 = %d\n", ret2);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2015-03-26
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多