Skip to content

Commit

Permalink
Fixed a CPU multithreading bug
Browse files Browse the repository at this point in the history
  • Loading branch information
yuanming-hu committed Jan 17, 2020
1 parent 8b08573 commit bd86b34
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
18 changes: 14 additions & 4 deletions taichi/system/threading.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ ThreadPool::ThreadPool() {
exiting = false;
started = false;
running_threads = 0;
timestamp = 0;
timestamp = 1;
last_finished = 0;
task_head = 0;
task_tail = 0;
thread_counter = 0;
Expand All @@ -84,6 +85,7 @@ void ThreadPool::run(int splits,
task_head = 0;
task_tail = splits;
timestamp++;
TC_ASSERT(timestamp < (1LL << 62)); // avoid overflowing here
}

// wake up all slaves
Expand Down Expand Up @@ -117,8 +119,14 @@ void ThreadPool::target() {
if (exiting) {
break;
} else {
started = true;
running_threads++;
if (last_finished >= last_timestamp) {
continue;
// This could happen when part of the desired threads wake up and finish all the task,
// and then this thread wake up finding nothing to do. Should skip this task directly.
} else {
started = true;
running_threads++;
}
}
}

Expand All @@ -137,8 +145,10 @@ void ThreadPool::target() {
{
std::lock_guard<std::mutex> lock(mutex);
running_threads--;
if (running_threads == 0)
if (running_threads == 0) {
all_finished = true;
last_finished = last_timestamp;
}
}
if (all_finished)
master_cv.notify_one();
Expand Down
1 change: 1 addition & 0 deletions taichi/system/threading.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class ThreadPool {
int max_num_threads;
int desired_num_threads;
uint64 timestamp;
uint64 last_finished;
bool started;
bool exiting;
CPUTaskFunc *func;
Expand Down

0 comments on commit bd86b34

Please sign in to comment.