【问题标题】:Synchronize all active threads C and release them one by one?同步所有活动线程C并一一释放?
【发布时间】:2017-03-29 06:14:25
【问题描述】:

C 中有没有办法让 C 程序中的所有线程,等待其他活动线程,然后按照它们来的顺序释放它们,就像 等待线程的队列? p>

【问题讨论】:

    标签: c multithreading synchronization queue


    【解决方案1】:

    我会试着给你一些我上学期做的笔记来帮助你......

    线程

    GCC 程序 -lpthread

    #include <pthread.h>
    int main(int argc, char *argv[]) {
    

    这会启动类/调度程序并将其命名为mulo

    pthread_mutex_t mulo = PTHREAD_MUTEX_INITIALIZER;
    

    这会启动一个条件来停止和开始线程的执行

    pthread_cond_t  c = PTHREAD_COND_INITIALIZER;
    

    定义将成为线程的结构

    pthread_t t1, t2, t3;
    pthread_t array[3];   // this is valid to set multiple variables
    

    定义你的范围/命名空间

    pthread_mutex_init(&mulo, NULL);
    

    创建进程

    pthread_create(&t1, NULL, printMessage, NULL);
    

    或者只是..

    fork(); 
    

    验证创建,线程 id 的类型为 pid_t (int)

    pid_t  pid;
    pid = fork();   // All child processes return 0.. if    error = -1  
    

    锁定(和解锁)一个函数,这样一次只能有一个进程运行它

    pthread_mutex_lock(&mulo);
    pthread_mutex_unlock(&mulo);
    

    用于发出解锁信号

    pthread_cond_signal(&c);
    pthread_cond_wait(&c, &mulo);
    

    所有使用线程的函数都必须是指向函数的指针

    void *printMessage() { …. } 
    pthread_create(&t1, NULL, printMessage, NULL);
    

    从线程中传递值

    pthread_create(&array[i], NULL, runCommand, (void *) &command);
    
    void *inc_count(void *idp) {
        int passed_in_value = *((int *) idp);
        .
        .
        .
    }
    

    完成它

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2017-11-20
      • 2014-12-01
      • 1970-01-01
      相关资源
      最近更新 更多