作者Shuhaur (D.K.)
看板C_and_CPP
標題[問題] 請教一個 thread 和 queue 的問題
時間Tue Mar 15 13:11:42 2022
問題(Question):
為什麼在一個 thread 裡把資料 push 進去,同一個 thread 還能拿的出資料,
但用另一個 thread 去拿就會拿不到資料呢?
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
https://ideone.com/zxlJa7
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.154.118 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1647321106.A.188.html
1F:→ ctrlbreak: 置底13戒-5 應該是吧XD 03/15 13:42
2F:→ Shuhaur: 好像是這樣…我來試試,感謝 03/15 15:06
3F:→ Schottky: 對就是一樓說的那樣 03/15 15:13
4F:推 Dracarys: 何不用std::string就好了?還有language mode設C++17以 03/15 15:30
5F:→ Dracarys: 上你的data會和std::data相撞 03/15 15:30
7F:→ Shuhaur: 哇,這程式碼好帥…之所以不用 string 是因為我後面要寫 03/15 16:41
8F:→ Shuhaur: socket, 所以會用到 byte 的 bitset... 03/15 16:42
9F:→ MasterChang: queue不是thread-safe的 03/15 23:25
10F:→ peter98: 你這問題應該跟thread沒關係 XD 03/16 03:21
11F:→ peter98: 不然你在outString印一下data.size()試試 肯定是1 03/16 03:22
12F:→ peter98: 你code的問題在於line 23那個str[10]不見了(local) 03/16 03:23
13F:→ Dracarys: 要c-style string可以再呼叫std::string::c_str可以跟 03/16 07:18
14F:→ Dracarys: 傳統C API對接,或是用string_view這種non-owning view 03/16 07:18
15F:→ Dracarys: 做操作,小弟一些淺見不知道這能不能符合你的需求。用s 03/16 07:18
16F:→ Dracarys: td::string好在它會取得那塊記憶體的ownership,不用自 03/16 07:18
17F:→ Dracarys: 己管理。 03/16 07:18
18F:→ Shuhaur: 嗯,跟thread沒關係,我試著直接call function 也是一樣 03/16 10:00
19F:→ Shuhaur: 改用string的話,socket 用 char[] 接資料轉存string 03/16 10:01
20F:→ Shuhaur: 另一個thread 可以拿出string, 但再用c_str 轉回 char 03/16 10:01
21F:→ Shuhaur: 資料就不是原本的樣子了~ 03/16 10:01
22F:推 Schottky: 今天的問題是和 thread 無關,但你這樣寫遲早踩到地雷 03/16 16:10
23F:→ tomsawyer: data那個不是全域變數嗎?跟第五戒有關? 03/20 04:57
24F:→ peter98: 是23行有問題 不是那個data有問題..................... 03/20 08:06
25F:推 dreamroad: local變數的記憶體指標離開scope之外無效,你要克服的 04/01 21:33
26F:→ dreamroad: 是記憶體管理的議題。 04/01 21:33