[英]Synchronizing stacks between threads
我正在使用客戶端(使用GUI和套接字)。 GUI(在主線程上運行)創建我的協議的fly命令,每次我創建一個新命令時,我將它附加到動態堆棧中。
在另一個線程(使用pthread)中,我檢查堆棧中是否有命令然后使用套接字(非塊btw)逐步發送它。 當堆棧頂部的命令完成后,我彈出堆棧(這意味着命令被刪除,第一個元素下面的每個命令都被推高)。
現在,你可能會猜到我有很大的問題要同步...我嘗試使用一些標志,互斥,但我總是最終在內存上有一些訪問沖突。
基本上我正在做的是這樣的:
在主線程中(即)用戶按下按鈕:
char cmd[ 50 ] = "My new protocol command";
AppendCommandToSendStack( cmd );
在另一個線程中:
if( SendStackCount )
{
SendCommand( 0 ); // 0 = The top of the stack.
if( IsCommandDoneSending( 0 ) )
{
RemoveCommandFromStack( 0 );
}
}
任何人都可以幫助我,或者給我一些關於如何使這個機制起作用的指示。 或者另一種方法會導致與我試圖實現相同或類似的工作流程。
事先提前!
[更新]
我開始閱讀信號量,它似乎正是我需要的......但它似乎不起作用......這就是我在偽代碼中做的事情:
sem_t mutex;
int stack_count;
command *stack;
main()
{
// Init & Connect client.
// Start Thread
sem_init( &lock_stack, 0, 1 );
while( 1 )
{
sem_wait( &lock_stack );
++stack_count;
stack = ( command * ) realloc( stack, stack_count * sizeof( command ) );
strcpy( stack[ stack_count - 1 ].cmd, "new command" );
sem_post( &lock_stack );
}
}
thread()
{
while( 1 )
{
sem_wait( &lock_stack );
if( stack_count )
{
// Send stack[ 0 ].cmd via socket then when done pop the stack like this:
--stack_count;
if( 0 < stack_count )
{
memcpy( &stack[ 0 ],
&stack[ 1 ],
( stack_count - 1 ) * sizeof( command ) );
}
}
sem_post( &lock_stack );
}
}
因為我基本上是新手,所以我錯過了一些明顯的東西,因為我仍然有內存訪問違規,“似乎”在堆棧數組上隨機發生。
你有一個生產者 - 消費者問題的典型例子。 您希望produce
命令,而其他線程consume
它們。 您可以查看http://en.wikipedia.org/wiki/Producer-consumer_problem ,它解釋了如何實現基本的生產者 - 消費者問題。
一個簡單的解決方案是:
Thread 1 :
lock mutex
put items on stack
unlock mutex
Thread 2 :
loop
lock mutex
check item on stack
if somthing get item on stack
unlock mutex
更有效的靈魂將是:
Thread 1 :
lock mutex
put items on stack
signal on conditionVariable
unlock mutex
Thread 2 :
lock mutex
check item on stack
if none wait on conditionVariable
// here you will be woke up when there is a signal
get item on the stack
unlock mutex
do your work
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.