在多线程编程中,当一个线程需要等待某个先决条件完成时,通常会使用同步机制来确保线程安全和正确的执行顺序。以下是一些常见的方法和技术:
互斥锁是一种同步原语,用于保护共享资源,防止多个线程同时访问。当一个线程获得锁时,其他试图获得该锁的线程将被阻塞,直到锁被释放。
示例代码(C++):
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
bool ready = false;
void worker_thread() {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) {
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
lock.lock();
}
// 先决条件已满足,继续执行
std::cout << "Worker thread is processing data...\n";
}
void main_thread() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
std::cout << "Main thread signals data ready.\n";
}
int main() {
std::thread worker(worker_thread);
main_thread();
worker.join();
return 0;
}
条件变量允许线程在某个条件为真之前一直等待。当条件满足时,另一个线程可以通知等待的线程继续执行。
示例代码(C++):
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker_thread() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
// 先决条件已满足,继续执行
std::cout << "Worker thread is processing data...\n";
}
void main_thread() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
std::cout << "Main thread signals data ready.\n";
}
int main() {
std::thread worker(worker_thread);
main_thread();
worker.join();
return 0;
}
信号量是一种计数器,用于控制多个线程对共享资源的访问。当计数器为零时,试图获取信号量的线程将被阻塞。
示例代码(Python):
import threading
import time
semaphore = threading.Semaphore(0)
ready = False
def worker():
semaphore.acquire()
print("Worker thread is processing data...")
def main():
global ready
time.sleep(1)
ready = True
print("Main thread signals data ready.")
semaphore.release()
t = threading.Thread(target=worker)
t.start()
main()
t.join()
在某些编程语言中,如Java和C++11,可以使用Future和Promise来处理异步操作的结果。Future表示一个可能还没有完成的异步操作的结果,而Promise用于设置这个结果。
示例代码(Java):
import java.util.concurrent.*;
public class AsyncExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(() -> {
Thread.sleep(1000);
return "Data is ready";
});
System.out.println("Main thread waiting for data...");
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
通过以上方法和示例代码,可以实现线程在先决条件未完成时的等待,并在条件满足后恢复执行。
领取专属 10元无门槛券
手把手带您无忧上云