起个线程
1.QT

1 #ifndef DIALOG_H 2 #define DIALOG_H 3 4 #include <QDialog> 5 #include <QThread> 6 #include <QString> 7 #include <QPushButton> 8 #include <QDebug> 9 #include <QCloseEvent> 10 #include <QMutex> 11 12 class MyThread :public QThread 13 { 14 public: 15 MyThread(); 16 void setMessage(const QString &msg); 17 void stop(); 18 19 protected: 20 void run() override; 21 22 private: 23 QString msg; 24 volatile bool bStop; 25 QMutex mutex; 26 }; 27 28 class Dialog : public QDialog 29 { 30 Q_OBJECT 31 32 public: 33 Dialog(QWidget *parent = nullptr); 34 ~Dialog(); 35 36 protected: 37 void closeEvent(QCloseEvent *) override; 38 39 private slots: 40 void startOrStopThreadA(); 41 void startOrStopThreadB(); 42 43 private: 44 MyThread threadA; 45 MyThread threadB; 46 QPushButton *bt_A; 47 QPushButton *bt_B; 48 }; 49 #endif // DIALOG_H

1 #include "dialog.h" 2 #include <iostream> 3 #include<QHBoxLayout> 4 5 Dialog::Dialog(QWidget *parent) 6 : QDialog(parent) 7 { 8 bt_A = new QPushButton(tr("Start A")); 9 bt_B = new QPushButton(tr("Start B")); 10 11 QHBoxLayout* layout = new QHBoxLayout(); 12 layout->addWidget(bt_A); 13 layout->addWidget(bt_B); 14 this->setLayout(layout); 15 16 connect(bt_A,SIGNAL(clicked()),this,SLOT(startOrStopThreadA())); 17 connect(bt_B,SIGNAL(clicked()),this,SLOT(startOrStopThreadB())); 18 19 threadA.setMessage("A"); 20 threadB.setMessage("B"); 21 } 22 23 Dialog::~Dialog() 24 { 25 } 26 27 void Dialog::startOrStopThreadA() 28 { 29 if(threadA.isRunning()){ 30 threadA.stop(); 31 bt_A->setText(tr("Start A")); 32 }else{ 33 threadA.start(); 34 bt_A->setText(tr("Stop A")); 35 } 36 } 37 38 void Dialog::startOrStopThreadB() 39 { 40 if(threadB.isRunning()){ 41 threadB.stop(); 42 bt_B->setText(tr("Start B")); 43 }else{ 44 threadB.start(); 45 bt_B->setText(tr("Stop B")); 46 } 47 } 48 void Dialog::closeEvent(QCloseEvent *event) 49 { 50 threadA.stop(); 51 threadB.stop(); 52 threadA.wait(); 53 threadB.wait(); 54 event->accept(); 55 } 56 57 //MyThread 58 MyThread::MyThread(){ 59 bStop = false; 60 } 61 void MyThread::run() 62 { 63 forever{ 64 QMutexLocker locker(&mutex); 65 if(bStop){ 66 bStop = false; 67 break; 68 } 69 std::cerr<<qPrintable(msg); 70 QThread::usleep(1500); 71 } 72 std::cerr<<"\r\n"; 73 } 74 void MyThread::stop() 75 { 76 QMutexLocker locker(&mutex); 77 bStop = true; 78 } 79 void MyThread::setMessage(const QString &msg) 80 { 81 this->msg = msg; 82 }

1 #include "dialog.h" 2 3 #include <QApplication> 4 5 int main(int argc, char *argv[]) 6 { 7 QApplication a(argc, argv); 8 Dialog w; 9 w.show(); 10 return a.exec(); 11 }

1 QT += core gui 2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 5 CONFIG += c++11 6 7 # The following define makes your compiler emit warnings if you use 8 # any Qt feature that has been marked deprecated (the exact warnings 9 # depend on your compiler). Please consult the documentation of the 10 # deprecated API in order to know how to port your code away from it. 11 DEFINES += QT_DEPRECATED_WARNINGS 12 13 # You can also make your code fail to compile if it uses deprecated APIs. 14 # In order to do so, uncomment the following line. 15 # You can also select to disable deprecated APIs only up to a certain version of Qt. 16 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 17 18 SOURCES += \ 19 main.cpp \ 20 dialog.cpp 21 22 HEADERS += \ 23 dialog.h 24 25 # Default rules for deployment. 26 qnx: target.path = /tmp/$${TARGET}/bin 27 else: unix:!android: target.path = /opt/$${TARGET}/bin 28 !isEmpty(target.path): INSTALLS += target
2.C++: std::thread

1 #include <iostream> 2 #include <thread> 3 #include <chrono> 4 #include <mutex> 5 6 using namespace std; 7 8 //#define MUTEX_ON 9 mutex g_mutex; 10 11 void f1(int& argc){ 12 thread::id ID = this_thread::get_id(); 13 14 #ifdef MUTEX_ON 15 g_mutex.lock(); 16 #endif 17 18 cout << "In function f1 ID:" << ID << endl; 19 20 #ifdef MUTEX_ON 21 g_mutex.unlock(); 22 #endif 23 this_thread::sleep_for(chrono::seconds(1)); 24 } 25 26 void f2(int argc){ 27 cout << "In function f2 argc=:" << argc << endl; 28 this_thread::sleep_for(chrono::seconds(1)); 29 } 30 31 class testClass{ 32 public: 33 34 void operator() (){ 35 cout << "In testClass()" << endl; 36 this_thread::sleep_for(chrono::seconds(1)); 37 } 38 }; 39 40 int main() 41 { 42 cout << "------In main" << endl; 43 44 int n = 0; 45 46 thread th1(f1, std::ref(n)); 47 thread th2(f2,6); 48 thread th3((testClass())); 49 50 cout << "------ start--- Blocks the current thread until the thread identified by *this finishes its execution" << endl; 51 cout << "th1 is joinable? " << th1.joinable() << endl; 52 53 th1.join(); 54 th2.join(); 55 th3.join(); 56 cout << "------ end ---" << endl; 57 58 system("pause"); 59 return 0; 60 }
3.Windows: HANDLE CreateThread( ... );

1 /* 2 HANDLE CreateThread( 3 LPSECURITY_ATTRIBUTES lpThreadAttributes, //SD : 线程安全相关的属性 ,常置为NULL 4 SIZE_T dwStackSize, //initialstacksize: 新线程的初始化栈的大小 ,可设置为0 5 LPTHREAD_START_ROUTINE lpStartAddress, //threadfunction : 被线程执行的回调函数 ,也称为线程函数 6 LPVOID lpParameter, //threadargument : 传入线程函数的参数 ,不需传递参数时为NULL 7 DWORD dwCreationFlags, //creationoption : 控制线程创建的标志 8 LPDWORD lpThreadId //threadidentifier: 传出参数,用于获得线程ID,如果为NULL则不返回线程ID 9 ); 10 11 HANDLE WINAPI CreateMutex( 12 LPSECURITY_ATTRIBUTES lpMutexAttributes, //线程安全相关的属性,常置为NULL 13 BOOL bInitialOwner, //创建Mutex时的当前线程是否拥有Mutex的所有权 14 LPCTSTR lpName //Mutex的名称 15 ); 16 17 DWORD WINAPI WaitForSingleObject( 18 HANDLE hHandle, //要获取的锁的句柄 19 DWORD dwMilliseconds //超时间隔 20 ); 21 22 BOOL WINAPI ReleaseMutex(HANDLE hMutex); 23 */ 24 25 #include <iostream> 26 #include <windows.h> 27 28 using std::cout; 29 30 HANDLE hMutex = NULL; 31 32 DWORD WINAPI Fun(LPVOID lpParamter){ 33 WaitForSingleObject(hMutex, INFINITE); 34 35 cout << "In Fun lpParamter = " << *(int*)(lpParamter) << "\n"; 36 Sleep(1000); 37 38 ReleaseMutex(hMutex); 39 return 0L; 40 } 41 42 int main(){ 43 cout <<"In main \n"; 44 45 int paramter = 10; 46 hMutex = CreateMutex(NULL, FALSE, L"test");//使用的是unicode环境,函数自动调用的是CreateMutexW宽字符函数,所以参数LPCTSTR 是LPCWSTR类型的,加_T(),TEXT(),或L(字符) 47 48 unsigned long ulThreadId = 0; 49 HANDLE hThread = CreateThread(NULL, 0, Fun, ¶mter, 0, &ulThreadId); 50 51 WaitForSingleObject(hMutex, INFINITE); 52 cout << "thread ID = " << ulThreadId << "\r\n"; 53 Sleep(1000); 54 ReleaseMutex(hMutex); 55 56 CloseHandle(hThread); //CloseHandle是关闭线程句柄,用来释放线程资源的,不是终止线程的 57 58 system("pause"); 59 return 0; 60 }
4.POSIX: int iRet = pthread_create(&hHandle, NULL, Fun, NULL);

1 /* 2 int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, 3 (void*)(*start_rtn)(void*), void *arg); 4 tidp:第一个参数为指向线程标识符的指针。 5 attr:第二个参数用来设置线程属性。 6 start_rtn:第三个参数是线程运行函数的起始地址。 7 arg:最后一个参数是运行函数的参数。 8 若线程创建成功,则返回0。 9 若线程创建失败,则返回出错编号,并且*thread中的内容是未定义的;返回成功时, 10 由tidp指向的内存单元被设置为新创建线程的线程ID。 11 g++ -o example example.c -lpthread 12 */ 13 14 #include <iostream> 15 #include <pthread.h> 16 #include <unistd.h> 17 18 using namespace std; 19 20 static const int g_iRunTime = 5000; 21 22 void* Fun(void* ptr) 23 { 24 int iRunTime = 0; 25 while (++iRunTime< g_iRunTime) 26 { 27 cout << "Fun() is running!" << endl; 28 usleep(10000); 29 } 30 } 31 32 33 int main() 34 { 35 pthread_t hHandle; 36 int iRet = pthread_create(&hHandle, NULL, Fun, NULL); //create a thread; 37 if (0 != iRet) 38 { 39 cout << "Create thread failed!" << endl; 40 } 41 sleep(1); 42 int iRunTime = 0; 43 while (++iRunTime<g_iRunTime) 44 { 45 cout << "main is running! " << endl; 46 usleep(10000); 47 } 48 sleep(1000); 49 return 0; 50 }
5.Java

1 //concurrency/liftoff.java 2 3 class LiftOff implements Runnable{ 4 protected int countDown = 10; 5 private static int taskCount = 0; 6 private final int id = (++taskCount); 7 public String status(){ 8 return "#" + id + "(" + 9 ((countDown > 0) ? countDown:"LiftOff") + "),"; 10 } 11 public void run(){ 12 while(countDown-- > 0){ 13 System.out.print(status()); 14 Thread.yield(); //suggest schedule 15 } 16 } 17 } 18 19 public class BasicThread{ 20 public static void main(String[] args){ 21 for(int i = 0;i < 3;i++){ 22 Thread th = new Thread(new LiftOff()); 23 th.start(); 24 } 25 System.out.println("Main task wait for LiftOff..."); 26 } 27 }
6.Python

1 #!/usr/bin/python3 2 3 import threading 4 import time 5 6 class testThread(threading.Thread): 7 def __init__(self,threadID,name,counter): 8 threading.Thread.__init__(self) 9 self.threadID = threadID 10 self.name = name 11 self.counter = counter 12 def run(self): 13 print("start thread..." + self.name) 14 print_time(self.name,self.counter,5) 15 print("stop thread..." + self.name) 16 17 def print_time(threadName,delay,counter): 18 while counter: 19 time.sleep(delay) 20 print("%s:%s" % (threadName,time.ctime(time.time()))) 21 counter -= 1 22 23 #create 24 thread_1 = testThread(1,"Thread-1",1) 25 26 27 #start 28 thread_1.start() 29 thread_1.join() 30 31 print("exit main thread")
分类:
并发(concurrent)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通