Article

From:
To:
All
Subject:
Thread safety with UnicodeString type [Edit]
Newsgroup:
embarcadero.public.cppbuilder.language.cpp

Thread safety with UnicodeString type [Edit]

I am considering using UnicodeString in threaded program so thread safety comes to mind.

Let's suppose you have a structure like this:
{code}
struct TTaskListEntry
{
int TaskID;
UnicodeString TaskText;

TTaskListEntry(int ATaskID, UnicodeString ATaskText) : TaskID(ATaskID), TaskText(ATaskText) {}
};

// Private members in thread class, not accesible from main thread private: boost::mutex QueueLock;            std::vector<TTaskListEntry> tasklist; {code}
It is passed along in following manner:
{code} void QueueAdd(const TTaskListEntry &TaskList) { boost::lock_guard<boost::mutex> lock(QueueLock); tasklist.push_back(TaskList);
// Maybe better alternative - copy UnicodeString to prevent reference counting from 2 threads?
//tasklist.push_back(TTaskListEntry(TaskList.TaskID, TaskList.TaskTxt.c_str());
}

TTaskListEntry QueueRead(unsigned Pos) { boost::lock_guard<boost::mutex> lock(QueueLock); return tasklist[Pos]; // Better alternative? //return TTaskListEntry(tasklist[Pos].TaskID, tasklist[Pos].TaskText); }
// Example call from main thread TTaskListEntry entry(123, "abc"); QueueAdd(entry); {code}
Now assuming 2 threads share this task list throudh Queue functions (and possibly others like QueueDel, QueueRearrange etc.) which of course are protected by boost::mutex, is the above sufficient to protect it against possible issues with UnicodeString reference counting being accessed from 2 threads? The way I understand it - reference counting is disabled when you use const UnicodeString reference as in above structure.

Each thread creates its own local TTaskListEntry variable which then is retrieved or sent to Queue functions. And main thread would only use QueueAdd function and possibly QueueSize (which gets tasklist size).

Should I be looking at copying strings or maybe passing pointer to wchar_t instead?
FYI: Phrase searches are enclosed in either single or double quotes
 
 
Originally created by
Tamarack Associates
Thu, 14 Nov 2024 17:36:49 UTC
Copyright © 2009-2024
HREF Tools Corp.