并行运行两个独立的线程

时间:2013-04-09 05:19:12

标签: c multithreading sockets

我编写了一个包含两个线程的服务器程序:

1. For sending data to client side.
2. For receiving data from client side

现在执行它们时,服务器接受请求并创建发送数据的线程,它开始向客户端发送数据,但由于它是可连接的,它将执行直到它完成执行并且另一个线程没有被创建控件仍然在这个帖子中。

为了使两个线程同时运行,我需要应用什么?

2 个答案:

答案 0 :(得分:2)

我想你可能在寻找pthread。这是我在学习线程如何工作时编写的示例代码。它是一个柜台。第一个线程每一个向一个变量添加一个,另一个将其打印出来。

#include<pthread.h>     //for simultanius threads
#include<stdio.h>
#include<stdlib.h>      //for the _sleep function

//global variables, both thread can reach thease.
int a = 0;
int run = 1;

void *fv(void)
{
   while( run )
    {
         _sleep(1000);
         a++;
    }
}

int main(){
    pthread_t thread;
    pthread_create( &thread, 0, fv, 0 );
    printf( "%d", a );
    while( a < 60 )
    {
        int last = a;
        while( last == a )
           _sleep(50); //let's not burn the cpu.
        printf( "\r%d", a );
        _sleep(500); //a won't change for a while
    }
    run = 0;
    pthread_join( thread, NULL );
    return 0;
}

答案 1 :(得分:0)

我没有误解这个概念,但问题是我正在执行以下步骤:

    1. creating sending thread.
    2. Making it joinable.
    3. creating receiving thread.
    4. Making it joinable.

现在发生了什么,一旦发送线程线程可以连接,就没有创建接收线程。 现在问题得到解决正确的顺序是:

    1. creating sending thread.
    2. creating receiving thread.
    3. Making  sending thread joinable
    4. Making  receiving thread joinable.

现在首先创建两个线程然后并行执行。

相关问题