c - 线程在pthread_create之后立即执行?

标签 c multithreading pthreads

当我创建 T 线程时,我在主线程中有以下代码。

pthread_t threads[T];
for (a=0; a<T; a++) {
    pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");

它创建了第一个线程,我注意到它立即开始执行第一个线程。 foo 为第一个线程调用,之后输出“in main thread”。我的实际意图是首先创建所有 T 线程(将线程插入“就绪”队列),然后继续在主线程中执行代码,直到它退出或产生。一旦 main 退出,我希望执行其中一个 T 线程。

在 foo 函数中:

void foo(pthread_t *threads, pthread_mutex_t **locks, double **transition) {
    printf("in foo\n");
}

在main_thread函数中:

void main_thread (int *N, int *T) {
    double **transition;
    pthread_mutex_t **locks;

    transition = malloc(*N * sizeof *transition);
    locks = malloc(*N * sizeof *locks);
    for (a=0; a< *N; a++) {
        transition[a] = malloc(*N * sizeof *transition[a]);
        locks[a] = malloc(*N * sizeof *locks[a]);
    }

    // lock for each element in transition matrix
    for (a=0; a<*N; a++) {
        for (b=0; b<*N; b++) {
            if (pthread_mutex_init(&(locks[a][b]), NULL) != 0) { 
                printf("\n mutex init has failed\n"); 
            }
        }
    }

    for (a=0; a<*N; a++) {
        for (b=0; b<*N; b++) {
            transition[a][b] = 0.0;
        }
    }

    pthread_t threads[T];
    for (a=0; a<T; a++) {
        pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
    }
    printf("in main thread\n");


}

在主函数中:

int main(int argc, char *argv[]) {

    int N = 4;
    int T = 2;

    pthread_t main_t;
    pthread_create(&main_t, NULL, &main_thread(&N, &T), NULL); 

    return 0;
}

最佳答案

使用 foo(...) 您可以调用 函数,将它的结果传递给 pthread_create 功能。这意味着该函数将在任何线程创建之前执行。

您需要传递一个指向线程函数的指针:

pthread_create(&threads[a], NULL, foo, NULL);

另请注意,当 main 函数退出时,通常会导致整个进程退出,这将杀死您已启动的所有线程。

如果您想在退出主线程线程后保持线程运行,那么您需要从主线程使用pthread_exit,然后分离您创建的线程。

为了不立即启动线程,IIRC 有一些属性可以设置并传递给 pthread_create 函数(第二个参数)以启动挂起的线程。不过,您必须显式恢复线程,这不会自动发生。

关于c - 线程在pthread_create之后立即执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553220/

相关文章:

c - 动画 'waiting' -CLI 模式下的符号

C - 结构作为参数

C 当条件为假时进入 if block

java - 使用多线程写入文件

c - Pthread编程: Segmentation Fault: 11 while using mutex

c - 用前一个 C 初始化结构变量

c - 如何在后台运行函数?

ios - 将单独线程检索的数据返回到主线程以在 UI 中显示

c++ - 什么时候调用 CloseHandle?

c++ - 获取错误 : ‘this’ is unavailable for static member functions even when function is not static