相关疑难解决方法(0)

函数的多个参数由pthread_create()调用?

我需要将多个参数传递给我想在一个单独的线程上调用的函数.我已经读过,执行此操作的典型方法是定义结构,向函数传递指向该结构的指针,并为参数取消引用它.但是,我无法让它工作:

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

struct arg_struct {
    int arg1;
    int arg2;
};

void *print_the_arguments(void *arguments)
{
    struct arg_struct *args = (struct arg_struct *)args;
    printf("%d\n", args -> arg1);
    printf("%d\n", args -> arg2);
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t some_thread;
    struct arg_struct args;
    args.arg1 = 5;
    args.arg2 = 7;

    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
        printf("Uh-oh!\n");
        return -1;
    }

    return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
Run Code Online (Sandbox Code Playgroud)

这个输出应该是:

5
7
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我实际得到: …

c pthreads

88
推荐指数
3
解决办法
15万
查看次数

将多个参数传递给C中的线程(pthread_create)

我试图将2个无符号整数传递给C中新创建的线程(使用pthread_create())但是也没有2个整数或结构的数组似乎有效.

// In my socket file

struct dimension {
    unsigned int width;
    unsigned int height;
};

unsigned int width, height;

void setUpSocket(void* dimension) {

    struct dimension* dim = (struct dimension*) dimension;

    width = dim->width;
    height = dim->height;

    printf("\n\nWidth: %d, Height: %d\n\n", width, height);

}

// In main.cpp

// Pass a struct in pthread_create
struct dimension dim;
dim.width = w;
dim.height = h;

pthread_create(&ph, &attr, (void * (*)(void *)) setUpSocket, (void *) &dim);
Run Code Online (Sandbox Code Playgroud)

在调用pthread_create之前,dim.width和dim.height是正确的.在我的套接字文件中,只设置了宽度,高度为0,我不明白为什么.

有谁知道什么是错的,请问如何解决?

非常感谢你.

c multithreading pthreads

6
推荐指数
1
解决办法
2万
查看次数

如何将多个值作为参数传递给C中的线程?

在C中,我如何将多个参数传递给线程?

通常情况下,我是这样做的,

 pthread_create(&th,NULL,dosomething,(void*)connfd);


void * dosomething(void *connfd)
{

  // Doing something      

}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我只将connfd值传递给线程'th'.

有没有办法传递多个值,以便它对我有用?

还有一件事,我们可以将数组作为参数传递给线程吗?

c pthreads

2
推荐指数
1
解决办法
990
查看次数

pthreads和C++

我正在玩C++和pthreads,到目前为止一直很好.我可以访问一个类成员函数,如果它是静态的,我已经读过,如果我将"this"作为参数传递给pthread_create,我可以访问普通的类成员函数,因为c ++是这样做的.但我的问题是我想给该函数一个int,我不知道如何用pthread_create做多个参数.

c++ pthreads

1
推荐指数
1
解决办法
433
查看次数

标签 统计

pthreads ×4

c ×3

c++ ×1

multithreading ×1