【问题标题】:C pthread_createC pthread_create
【发布时间】:2013-02-07 15:47:16
【问题描述】:
typedef struct client
{
   pthread thread;
   Window_t *win
}client;

client * client_create(int ID)
{
    client *new_Client = (client *) malloc(sizeof(client));
    char title[16];

    if (!new_Client) return NULL;

    sprintf(title, "Client %d", ID);

    /* Creates a window and set up a communication channel with it */
    if ((new_Client->win = window_create(title))) 
        return new_Client;
    else {
        free(new_Client);
        return NULL;
    }
}

当用户输入“e”时,我尝试使用新客户端和窗口创建一个新线程,这就是我的 int_main。 该标志只是告诉我用户输入了e

if(eflag == 1)
{    
    client *c = NULL;
    c=client_create(started);
    pthread_create(&c.thread, NULL, client_create, (void *) &started);
    started++;
    eflag =0;
}

这应该在新窗口的新线程上创建一个新客户端,但它没有这样做。

我不确定要在我的 pthread_create 中放入什么,以及我应该如何获取客户端的新实例,因为 client_create 函数会创建一个新窗口。当我尝试通过执行 pthread_create 创建一个新线程时,它还会创建一个新窗口...如果这是 java oeverytime 用户按“e”,我只会创建一个类客户端的新实例...但我可以' t真的在这里。有什么建议?

【问题讨论】:

  • 你的代码是做什么的?这个 window_create 函数是什么?
  • 最初这是一个单线程程序。 window_createe 创建一个新窗口,用户可以在其中与数据库交互,.我正在努力做到这一点,所以你可以拥有尽可能多的用户

标签: c multithreading pointers pthreads


【解决方案1】:

pthread_create函数的原型是

int pthread_create(pthread_t *restrict thread,
              const pthread_attr_t *restrict attr,
              void *(*start_routine)(void*), void *restrict arg);

您的 start_routine 定义需要匹配 void *(*start_routine)(void*).. 并且它在新的线程上下文中执行。

void *my_client_routine(void *arg) {
    while(1) {
        // do what each client does.
    }
}

目前在您的 main() 中,您正在执行您的 create_client 函数两次。一次是在调用 pthread_create() 之前,一次是作为从 pthread_create 产生的新线程的一部分。你可能想要做的是

  c = create_client()
  pthread_create(&c.thread, NULL, my_client_routine, &args_that_client_routine_needs);

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2015-08-13
    • 2011-12-18
    • 2017-01-01
    • 1970-01-01
    • 2012-01-05
    • 2013-07-10
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多