c - 线程未按预期工作

标签 c pthreads pthread-join

我很困惑为什么我的程序没有按预期运行。

我有三个类似的功能:

static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR); 

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L2(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L2", O_RDWR); 

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L3(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L3", O_RDWR); 

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

接下来我有一个创建线程的函数:

static void createKThread(void* (*a)(void *), void* (*b)(void *), void* (*c)(void *))

{
  pthread_t t1, t2, t3;
  int T1, T2, T3;

  T1 =  pthread_create(&t1, NULL, a, NULL);
  T2 =  pthread_create(&t2, NULL, b, NULL);
  T3 =  pthread_create(&td3, NULL, c, NULL);

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

}

我主要做的是:

     int main(){

     Send2[0] = 'a';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

     Send2[0] = 'b';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //Second
     return 0;
     }

我的主程序在第一个函数调用“createKThread”完成后终止。我不明白为什么,我希望第二个函数调用能够工作,并且我想向我的主程序添加更多代码。请告诉我我做错了什么。

最佳答案

你搞乱了你的线程函数。 我假设您的函数 L1 等应该作为线程函数运行。

static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR); 

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

你的编译器不会大喊缺少返回值吗?

当您调用创建函数时,您将传递这些函数的返回值:

createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

您无需传递函数的地址,而是调用它们! 当它们返回随机值时,您可以使用随机函数地址创建线程。

关于c - 线程未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47285749/

相关文章:

c++ - 如何在c++中创建不同数量的线程?

c - pthread : join a detached thread doesn't set errno correctly

c - 冒泡排序选项。需要添加一个打印气泡位移的(print_bubble)程序

C++ 多线程 : terminate after throwing an instance of 'std::length_error'

c - 如何使用从线程函数返回到 main 中的结构指针?

pthreads - pthread 属性对象是否需要在使用它们的对象的生命周期内存在?

c - 使用 Struct 将字符串数组和索引传递给 C 中的线程

c++ - 如何使用 Glib(或任何其他库)列出目录中的所有文件?

c - 如何用C语言将长度添加到字符数组缓冲区的末尾

c - 如何更改代码以使输出等于节点中的所有数据元素?