写一个简单的多线程Cpp代码
时间: 2023-12-01 12:55:24 浏览: 23
Sure, here is a simple multi-threaded C++ code:
```
#include <iostream>
#include <thread>
using namespace std;
void printHello() {
cout << "Hello from thread " << this_thread::get_id() << endl;
}
int main() {
thread t1(printHello);
thread t2(printHello);
t1.join();
t2.join();
return 0;
}
```
This code creates two threads using the `thread` class and passes a function `printHello` to each thread. Each thread will print a message indicating which thread it is running on using the `this_thread::get_id()` function. The `join()` method is used to wait for the threads to finish executing before the program exits.
Hope that helps!
相关问题
写一个简单的带参数的多线程Cpp代码
我可以回答这个问题。以下是一个简单的带参数的多线程Cpp代码:
#include <iostream>
#include <thread>
void printMessage(std::string message) {
std::cout << message << std::endl;
}
int main() {
std::string message = "Hello, world!";
std::thread threadObj(printMessage, message);
threadObj.join();
return 0;
}
写一个qt 多线程 usb cdc 代码
以下是一个简单的Qt多线程USB CDC代码示例,用于从USB串口读取数据并显示到界面上:
```cpp
// main.cpp
#include <QCoreApplication>
#include "USBThread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
USBThread thread;
thread.start();
return a.exec();
}
```
```cpp
// USBThread.h
#ifndef USBTHREAD_H
#define USBTHREAD_H
#include <QObject>
#include <QThread>
#include <QSerialPort>
#include <QSerialPortInfo>
class USBThread : public QThread
{
Q_OBJECT
public:
explicit USBThread(QObject *parent = nullptr);
~USBThread();
protected:
void run() override;
signals:
void dataReceived(const QByteArray& data);
private:
QSerialPort* m_serialPort;
};
#endif // USBTHREAD_H
```
```cpp
// USBThread.cpp
#include "USBThread.h"
USBThread::USBThread(QObject *parent) : QThread(parent)
{
m_serialPort = new QSerialPort(this);
m_serialPort->setPortName("COM3"); // 设置串口号
m_serialPort->setBaudRate(QSerialPort::Baud115200); // 设置波特率
if (!m_serialPort->open(QIODevice::ReadWrite)) {
qDebug() << "Failed to open serial port!";
}
}
USBThread::~USBThread()
{
if (m_serialPort->isOpen()) {
m_serialPort->close();
}
}
void USBThread::run()
{
while (1) {
if (m_serialPort->waitForReadyRead(100)) {
QByteArray data = m_serialPort->readAll();
emit dataReceived(data);
}
}
}
```
在上述代码中,我们创建了一个名为`USBThread`的类,继承自`QThread`。在构造函数中,我们创建了一个`QSerialPort`对象,并设置串口号和波特率。在`run()`函数中,我们使用`waitForReadyRead()`函数来等待串口有数据可读,然后读取数据并通过信号`dataReceived()`发送出去。
在主线程中,我们创建了一个`USBThread`对象,并调用`start()`函数来启动线程。在`dataReceived()`信号的槽函数中,我们可以将接收到的数据显示到界面上。
需要注意的是,以上代码仅供参考,具体的USB CDC应用程序开发需要根据实际需求进行设计和实现。如果你对Qt的使用还不熟悉,建议你先学习Qt的基础知识,并参考相关文档和示例代码进行学习和练习。