尽管尝试创建两个线程,但只创建了一个线程 [英] Only one thread gets created despite the attempt to create two

查看:72
本文介绍了尽管尝试创建两个线程,但只创建了一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

FILE*            fp;
pthread_mutex_t demoMutex         = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  conditionVariable = PTHREAD_COND_INITIALIZER;
unsigned int    condition         = 0;

struct serverInfo
{
    unsigned int serverId;
    pthread_t    threadId;
    std::vector<std::string> queue;
};
std::vector<serverInfo> serverInfoVector;

void* printHello(void* threadId)
{
    pthread_t* my_tid = (pthread_t*)threadId;

    pthread_mutex_lock(&demoMutex);
    while (condition == 0)
        pthread_cond_wait(&conditionVariable, &demoMutex);

    unsigned int i = 0;
    char found = false;

    if (serverInfoVector.size () > 0) {
       while ((i <= serverInfoVector.size()) && (found == false)) {
          if (*my_tid == serverInfoVector[i].threadId) {
             found = true;
             break;
          }
          else
             i++;
       }
    }

    while (!serverInfoVector[i].queue.empty()) {
       std::cout << "\nThread: " << pthread_self() << ", poped from queue: " << serverInfoVector[i].queue.front();
       serverInfoVector[i].queue.pop_back();
    }

    pthread_mutex_unlock(&demoMutex);
    pthread_exit(NULL);
}

void checkServerExists(unsigned int serverNumber, std::string message)
{
    unsigned int i = 0;
    char found = false;

    pthread_mutex_lock(&demoMutex);

    if (serverInfoVector.size () > 0) {
       while ((i <= serverInfoVector.size()) && (found == false)) {
          if (serverNumber == serverInfoVector[i].serverId) {
             found = true;
             break;
          }
          else
             i++;
       }
    }

    if (found == false) {
       // This server doesn't exist, so create a thread for it, create a queue for it, push the message in the corresponding queue.
       // Push the server number in the serverNumberArray.

       // Create a thread for it.
       pthread_t newThread;
       int returnValue;
       if ((returnValue = pthread_create (&newThread, NULL, printHello, (void*) &newThread)) != 0) {
          printf("\nerror: pthread_create failed with error number %d", returnValue);
       }
       printf("\nIn checkServerExists()`: thread id %ld\n", newThread);

       // Push the message in its queue.
       serverInfo obj;
       obj.serverId = serverNumber;
       obj.threadId = newThread;
       obj.queue.push_back(message);
       serverInfoVector.push_back(obj);

       condition++;
       pthread_cond_signal(&conditionVariable);
       pthread_mutex_unlock(&demoMutex);

       for (unsigned int i = 0; i < serverInfoVector.size(); i++)
          pthread_join(serverInfoVector[i].threadId, NULL);
    }
    else {
       // This server exists, so lookup its thread and queue, push the message in the corresponding queue.
       printf("\nIn else ()`: thread id %ld\n", serverInfoVector[i].threadId);
       serverInfoVector[i].queue.push_back(message);

       condition++;
       pthread_cond_signal(&conditionVariable);
       pthread_mutex_unlock(&demoMutex);

       for (unsigned int i = 0; i < serverInfoVector.size(); i++)
          pthread_join(serverInfoVector[i].threadId, NULL);
    }
}

int main()
{
   fp = fopen("xyz", "w");

   checkServerExists(1, "anisha");
   checkServerExists(2, "kaul");
   checkServerExists(1, "sanjeev");
   checkServerExists(2, "sharma");
}

输出:

In checkServerExists ()`: thread id 140233482061584

Thread: 140233482061584, poped from queue: anisha
In checkServerExists ()`: thread id 140233482061584

In else ()`: thread id 140233482061584

In else ()`: thread id 140233482061584

问题是似乎只有一个线程被创建!我在 main() 中调用了函数 checkServerExists 4 次,用不同的 serverID 调用了 2 次,所以应该创建两个线程?

The problem is that it seems that only one thread is getting created! I have called the function checkServerExists 4 times in main() and 2 times with different serverID, so two threads should be created?

我错过了什么?

推荐答案

我不确定这是否会导致行为,但以下是错误:

I am unsure if this is contributing to the behaviour, but the following is an error:

while ((i <= serverInfoVector.size ()) && (found == false))
{
    if (serverNumber == serverInfoVector [i].serverId)
    {
        found = true;
        break;
    }
    else
        i++;
}

由于if 中的<= 条件,

serverInfoVector[i] 将访问一个太多.更改为:

serverInfoVector[i] will be accessing one too many due to the <= condition in the if. Change to:

while ((i < serverInfoVector.size ()) && (found == false))

认为这是问题所在:当 checkServerExists() 被调用时,它似乎在等待它开始完成的线程:

I think this is the problem: when checkServerExists() is called, it seems to wait for the thread that it started to complete:

for (unsigned int i = 0; i < serverInfoVector.size(); i++)
    pthread_join(serverInfoVector[i].threadId, NULL);

这意味着线程 ID 140233482061584 不再使用,并且可以再次与新线程关联.下次调用 checkServerExists() 时,线程 id 被重用,给人的印象是只启动了一个线程.

This means that thread id 140233482061584 is no longer in use and is available again to be associated with a new thread. When the next call to checkServerExists() is made the thread id is reused, giving the impression that only one thread was started.

编辑 2:

正如 Schwarz 指出的那样,这是不正确的:

As pointed out by Schwarz this is incorrect:

if (*my_tid == serverInfoVector[i].threadId) {

你需要使用pthread_equal()来比较两个pthread_t.更改为:

you need to use pthread_equal() to compare two pthread_t. Change to:

if (pthread_equal(*my_tid, serverInfoVector[i].threadId)) {

或者将 serverId 作为参数传递给线程.

or alternatively pass the serverId as the argument to the thread.

这篇关于尽管尝试创建两个线程,但只创建了一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆