2

我正在处理客户端运行两个线程的客户端服务器代码;我希望这两个线程连续运行 60 秒。但是,我面临两个问题。

首先,当我在 中运行 for 循环时main()retail_thread()生成的数字与它应该生成的随机数相同,就像bulk_thread()生成一样。其次,我无法理解恰好运行 60 秒的 for 循环。

由于这是一个家庭作业问题,如果不是确切的解决方案,我将非常感谢任何提示或帮助。如果有错别字,请忽略。

int main(int argc, char *argv[]) {

    int pt,i;
    pthread_t thread;
    /* n a very large number */
    /* run below code for 60 seconds */

    for(i=0;i<n;i++)
    {
        pt = pthread_create(&thread, NULL, retail_thread, (void*) NULL);
        bulk_thread(NULL);
    }
}

void* retail_thread(void* ){
    srand(time(NULL));                       
    int order_size = rand()%20 + 1;         
    printf("in retail \n ");
    sendtoserver_R(RETAIL_PORT,order_size);
    int wait_time = 100 + (5*order_size);
    printf("Retail thread order = %d and execution fully completed \n\n",order_size);
}

void* bulk_thread(void* ){
    srand(time(NULL));                      
    int order_size = rand()%90 + 10;        
    printf("in bulk \n");
    int wait_time = 100 + (5*order_size);
    sendtoserver_B(BULK_PORT,order_size);

    printf("Bulk thread order = %d and execution fully completed \n\n",order_size);
}

sendtoserver()仅用于创建套接字并将数据发送到服务器。

4

1 回答 1

3

好吧,我认为第一个问题是:

// Seed the RNG once, at the start of the program
srand(time(NULL));  

void* retail_thread(void* ){
    //srand(time(NULL));                       
    int order_size = rand()%20 + 1;         
    printf("in retail \n ");
    sendtoserver_R(RETAIL_PORT,order_size);
    int wait_time = 100 + (5*order_size);
    printf("Retail thread order = %d and execution fully completed \n\n",order_size);
  }

[编辑]要运行一个线程 60 秒,你可以试试这个:

time_t end = time(NULL) + 60;
while (time(NULL) <= end)
{
    … // do something
}
于 2013-03-16T10:30:33.483 回答