c - 如何在线程中共享内存

标签 c linux multithreading

我试图在线程函数中使用我在主函数中分配的内存,但出现错误:undefined reference to 'product_line'

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "test1.c"

int main()
{
    char** product_line;
    product_line = malloc(sizeof(char *));

    product_line[0] = "Toy";    
    product_line[1] = "Chair";
    product_line[2] = "Door";

    pthread_t thread_tid;
    pthread_create(&thread_tid, NULL, foo, NULL);

    pthread_join(thread_tid, NULL);

return 0;
}

这是线程调用的独立源:

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

extern char** product_line;

void * foo(void *param)
{
    int i;
    printf("%s\n", product_line[0]);
    for (i = 0; i < 3; i++)
        printf("%s\n", product_line[i]);
}

我该如何修复这个错误?

最佳答案

变量product_line 应该在main 之外声明,否则其他翻译单元无法访问它:

/* main.c */
…

char **product_line;

int main()
{
    …
}

MikeCAT 提到的另一个问题:

Including .c source file is unusual.

考虑添加头文件test1.h:

/* test1.h */
#ifndef TEST1_H
#define TEST1_H

void * foo(void *param);

#endif

然后,将 main.c 中的 #include "test1.c" 替换为:

#include "test1.h"

main.ctest1.c 都被编译时,这是为了避免 foo 的重复定义。 (假设您正在使用类似于 cc main.c test1.c 的东西编译代码。)建议(尽管是可选的)在 中也包含 test1.h >test1.c.


Martin James 还提到:

You allocate space for one pointer, then use three of them:((

这一行

product_line = malloc(sizeof(char *));

为单个 char * 指针分配空间。但是,您实际上使用了其中的 3 个,因此您需要分配 3 个 char * 指针:

product_line = malloc(sizeof(char *) * 3);

关于c - 如何在线程中共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812048/

相关文章:

c - nptl SIGCONT 和线程调度

linux - 在 Ubuntu 12.04 中编译使用 glew 库的项目时出错

ruby - 如果列少于 4 打印第 3 列,如何 ruby ?

multithreading - 为什么比较和交换 (CAS) 算法是无锁同步的好选择?

c - 如何使用c在链表节点中传递两个参数?

c++ - 映射随机数

linux - 在 linux 中使用批处理文件启动多个 firefox 配置文件

java - 在多线程执行期间使用 TestNG 生成 Cucumber ExtentReport

multithreading - 为什么我的F#异步代码的第二个片段有效,而第一个无效?

c - 在函数中使用未声明的标识符