pthreads 运行 逆序

pthreads running in reverse order

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

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

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

Is there any way I can make sure the thread I create the first runs first?

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

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