Skip to content

WaitForJobsAndJoinAllThreads 接口具体含义请教 #2

Description

@ravenxrz

你好,对于这个函数,注释的说明如下:

  // Waits for all jobs to complete those
  // that already started running and those that did not
  // start yet
  void WaitForJobsAndJoinAllThreads() override;

没理解错的话,应该是会等待所有task(包括开始和没有开始)执行完成,才返回。
但实际在使用的使用,并没执行所有task,一个例子如下:

std::atomic_int g_val{0};

void Thread1(void *arg) {
  g_val++;
  usleep(1000);
}

void Thread2(void *arg) {
  g_val++;
  usleep(1000);
}

int main(int argc, char *argv[]) {
  std::atomic<int> last_id(0);

  auto *thread_pool1 = new ThreadPoolImpl();
  auto *thread_pool2 = new ThreadPoolImpl();

  thread_pool1->SetBackgroundThreads(1);
  thread_pool1->SetThreadPriority(Env::HIGH);
  thread_pool2->SetBackgroundThreads(1);
  thread_pool1->SetThreadPriority(Env::LOW);

  for (int i = 0; i < 100000; i++) {
    if (i & 1) {
      thread_pool1->Schedule(Thread1, nullptr, nullptr, nullptr);
    } else {
      thread_pool2->Schedule(Thread2, nullptr, nullptr, nullptr);
    }
  }
  std::cout << "threadpool1 len:" << thread_pool1->GetQueueLen() << std::endl;
  std::cout << "threadpool2 len:" << thread_pool2->GetQueueLen() << std::endl;
  thread_pool1->WaitForJobsAndJoinAllThreads();
  thread_pool2->WaitForJobsAndJoinAllThreads();
  // thread_pool1->JoinAllThreads();
  // thread_pool2->JoinAllThreads();
  std::cout << "finish all " << g_val << std::endl;
  return 0;
}

打印结果:

threadpool1 len:49991
threadpool2 len:49991
finish all 19

我理想中的结果最后应该是 finish all: 100000
不知道是不是我哪里理解错误了。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions