| |

VerySource

 Forgot password?
 Register
Search
View: 912|Reply: 5

Questions about concurrency and locks

[Copy link]

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

Post time: 2020-3-3 12:30:01
| Show all posts |Read mode
+ ---- + ---------- + --------- +
| id | item | status |
+ ---- + ---------- + --------- +
| 1 | a | 1 |
+ ---- + ---------- + --------- +
| 2 | b | 0 |
+ ---- + ---------- + --------- +
| 3 | c | 0 |
+ ---- + ---------- + --------- +
| 4 | d | 0 |
+ ---- + ---------- + --------- +
| 5 | e | 0 |
+ ---- + ---------- + --------- +
| 6 | f | 0 |
+ ---- + ---------- + --------- +
| 7 | g | 0 |
+ ---- + ---------- + --------- +

There is a program that polls this table every time and selects the record with select top 1 * from tbl where status = 0, and then sets the status of this record to 1. The problem is that if it is multi-threaded, a thread may appear. This record has been fetched. Before it sets this record to 1, another thread fetches this record, and it appears that multiple identical data records have been fetched. How do you solve this problem?
Reply

Use magic Report

0

Threads

114

Posts

69.00

Credits

Newbie

Rank: 1

Credits
69.00

 China

Post time: 2020-5-15 06:45:01
| Show all posts
When fetching, add non-zero conditions?
Reply

Use magic Report

1

Threads

2

Posts

3.00

Credits

Newbie

Rank: 1

Credits
3.00

 China

 Author| Post time: 2020-5-16 17:00:01
| Show all posts
First take 0 and then update the retrieved record to 1
Reply

Use magic Report

0

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 Morocco

Post time: 2020-7-31 15:30:01
| Show all posts
You can update the status to 1:
update tbl set status = 1 from (select top 1 id from tbl where status=0) as t1 where tbl.id = t1.id
, And then use the trigger to get the information of the most recently updated row. This can avoid the problems mentioned by the original poster!
Reply

Use magic Report

0

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-7-31 15:45:01
| Show all posts
The statement in the trigger is written like this
if update(status)
begin
     select * from deleted, inserted where deleted.status = 0 and inserted.status = 1
end
Reply

Use magic Report

0

Threads

6

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-7-31 16:30:01
| Show all posts
There are too many return columns written above, it should be like this:
if update(status)
begin
     select deleted.id,deleted.item,deleted.status from deleted,inserted where deleted.status = 0 and inserted.status = 1
end
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list