【问题标题】:Pthread Programming Short ExamplePthread 编程简短示例
【发布时间】:2019-12-08 10:42:52
【问题描述】:

由于我是 pthread 编程的新手,所以我在理解这段代码时遇到了一些麻烦。据我了解,我们创建 N 个线程 并对其执行 run 函数,该函数仅打印线程号。我错过了什么吗?

在这种特殊情况下,与 printf 相比,使用 snprintf(带缓冲区)是否有任何优势?这个程序可以进一步改进吗?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

static int N = 5;
static void* run(void *arg)
{
    int *i = (int *) arg;
    char buf[123];
    snprintf(buf, sizeof(buf), "thread %d", *i);
    return buf;
}

int main(int argc, char *argv[])
{
   int i;
   pthread_t *pt = NULL;
   for (i = 0; i < N; i++) {
       pthread_create(pt, NULL, run, &i);
   }

   return EXIT_SUCCESS;
}

【问题讨论】:

    标签: c linux multithreading pthreads stdio


    【解决方案1】:

    首先,您的线程返回垃圾。推迟返回的指针将是未定义的行为,因为它指向函数返回后不再存在的存储。还好没有使用指针。

    接下来,线程不打印任何内容,因为 snprintf 输出到数组,而不是标准输出。

    此外,如果您切换到printf,线程将打印垃圾,因为相同的指针被传递给所有线程。

    这是假设线程有机会运行,因为main 不会等待线程完成。你必须加入他们。

    固定:

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define N 5
    
    static void *run(void *arg) {
        size_t job = *(size_t*)arg;
        printf("Job %zu\n", job);
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
       size_t jobs[N];
       pthread_t threads[N];
       for (size_t i=0; i<N; ++i) {
           jobs[i] = i;
           pthread_create(threads+i, NULL, run, jobs+i);
       }
    
       for (size_t i=0; i<N; ++i) {
           pthread_join(threads[i]);
       }
    
       return EXIT_SUCCESS;
    }
    

    将整数转换传递给指针也很常见。

    #include <inttypes.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <stdint.h>
    
    static void *run(void *arg) {
        size_t job = *(uintptr_t*)arg;
        printf("Job %" PRIuPTR "\n", job);
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
       pthread_t threads[N];
       for (uintptr_t i=0; i<N; ++i) {
           pthread_create(threads+i, NULL, run, (void*)i);
       }
    
       for (uintptr_t i=0; i<N; ++i) {
           pthread_join(threads[i]);
       }
    
       return EXIT_SUCCESS;
    }
    

    【讨论】:

    • 为了一致性,threads[i] 用 pthread_create 代替 threads+i
    • @artm、&amp;( threads[i] )threads+i,但不是 threads[i]
    • @ikegemi 啊我明白了 - 它必须是指向 pthread_t 的指针......很好的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多