Passing C-style strings between threads safely requires careful consideration due to the nature of shared memory and potential race conditions. Here are some approaches you can use:
const
StringsIf the string doesn't need to be modified, pass it as a const char*
. This ensures that the string won't be accidentally modified by any thread:
#include <iostream>
#include <thread>
void printString(const char* str) {
std::cout << "Thread received: " << str << '\n';
}
int main() {
const char* message{"Hello, World!"};
std::thread t{printString, message};
t.join();
}
Thread received: Hello, World!
If you need to modify the string, create a deep copy for each thread:
#include <iostream>
#include <thread>
#include <cstring>
void modifyString(char* str) {
strcat_s(str, 100, " Modified");
std::cout << "Thread modified: " << str << '\n';
}
int main() {
const char* original{"Hello, World!"};
char copy[100];
strcpy_s(copy, original);
std::thread t{modifyString, copy};
t.join();
std::cout << "Original unchanged: " << original;
}
Thread modified: Hello, World! Modified
Original unchanged: Hello, World!
If multiple threads need to access the same string, use synchronization primitives like mutexes:
#include <iostream>
#include <thread>
#include <mutex>
#include <cstring>
class SharedString {
char data[100];
std::mutex mtx;
public:
SharedString(const char* initial) {
strcpy_s(data, sizeof(data), initial);
}
void append(const char* str) {
std::lock_guard<std::mutex> lock{mtx};
strcat_s(data, sizeof(data), str);
}
void print() {
std::lock_guard<std::mutex> lock{mtx};
std::cout << data << '\n';
}
};
int main() {
SharedString shared{"Hello"};
std::thread t1{[&shared] {
shared.append(", World");
}};
// Ensure t1 completes before starting t2
t1.join();
std::thread t2{[&shared] {
shared.append("!");
}};
t2.join();
shared.print();
}
Hello, World!
Remember, when working with multithreaded applications, it's often safer and easier to use std::string
instead of C-style strings. std::string
provides thread-safe read operations and can be used with synchronization primitives for write operations.
Answers to questions are automatically generated and may not have been reviewed.
A guide to working with and manipulating C-style strings, using the
library