我正在做一些多线程编程。 它是一个多读者,单一作家模型。 我想我以正确的方式使用pthread_rwlock。当我分配给字符串并进入睡眠状态时,对字符串的赋值总是为空。 有人能告诉我我的代码有什么问题吗? THX。
#include "util/tc_thread.h"
#include "util/tc_thread_rwlock.h"
using namespace taf;
static string g_buffer;
static pthread_rwlock_t g_lock;
class TestThread: public TC_Thread
{
public:
TestThread(int type, const string &_msg): m_type(type), m_msg(_msg)
{
if (type == 2)
{
printf("writer get m_msg: %s\n", m_msg.c_str());
}
}
~TestThread()
{
//printf("Destroy thread of type %d\n", m_type);
}
protected:
void run()
{
if (m_type == 1)
{
//Reader
pthread_rwlock_rdlock(&g_lock);
printf("%s\n", g_buffer.c_str());
usleep(2000000); //FIXME::If I drop this line or move it below pthread_rwlock_unlock, the two ways of assign to g_buffer both take effects.
pthread_rwlock_unlock(&g_lock);
}
else if (m_type == 2)
{
//Writer
pthread_rwlock_wrlock(&g_lock);
printf("==succ: %s\n", g_buffer.c_str());
printf("==succ: %s\n", m_msg.c_str());
g_buffer = m_msg; //FIXME::Here, the g_buffer will be empty
//g_buffer = m_msg.data(); //FIXME:: If I assign g_buffer like this, the result is right.
printf("==succ: %s\n", g_buffer.c_str());
printf("==succ: %s\n", m_msg.c_str());
pthread_rwlock_unlock(&g_lock);
}
else if (m_type == 3)
{
while (1)
{
printf("type 3 thread is working\n");
sleep(1);
}
}
pthread_exit((void *)(0));
}
private:
int m_type;
string m_msg;
};
int main(int argc, char **argv)
{
pthread_rwlockattr_t attr;
pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_rwlock_init(&g_lock, &attr);
TestThread trd(3, "Hello1");
trd.start();
TestThread fst(2, "Hello1");
fst.start();
for (int i = 0; i < 10; ++i)
{
TestThread t(1, "Hello 9");
t.start();
}
TestThread snd(2, "Hello2");
snd.start();
for (int i = 0; i < 10; ++i)
{
TestThread t(1, "Hello 10");
t.start();
}
pthread_exit((void *)(0));
}
=============================================== ==
当作者线程snd尝试将g_buffer设置为&#34; Hello2&#34;时,g_buffer变为空。 TC_Thread是一个私人图书馆,我没有代码。但它经过了彻底的测试,所以不可能成为这个问题的原因。