|
|
|
|
|
|
T********i 发帖数: 2416 | 1 我现在就把这个实际的单机多线程抢票的算法贴出来。
goodbug号称NASDAQ处理股票交易的算法比这个简单,请TA实现以下给我们看看好不好?
/**************************************************************
///
/// param segmentTickets Tickets left in each segment of the entire
route.
/// param from The start index of the segment of the user requested
route.
/// param length The length of the user requested route.
///
/// return true if the route is successfully reserved; otherwise
false.
*/
bool reserveTicket(int *segmentTickets, int from, int length) {
int *curSegment = segmentTickets + from;
int *endSegment = curSegment + length;
while (curSegment < endSegment) {
int newCount = InterlockedDecrement(curSegment);
if (newCount < 0)
break;
curSegment++;
}
if (curSegment < endSegment) {
// Failed, return back reserved
endSegment = curSegment + 1;
curSegment = segmentTickets + from;
while (curSegment < endSegment) {
InterlockedIncrement(curSegment);
curSegment++;
}
return false;
} else
return true;
} | T********i 发帖数: 2416 | 2 其实这个实现不算是最优的,这个设计的每个路段的余票数量是一个int类型。才4个
byte。
其实最优的应该是一个cache line的大小,也就是64字节。保证了各个core不会锁定同
一个cache line。
可以定义:
struct TicketCount {
int count;
char dummy[60];
};
然后用这个TicketCount ×类型替换上面的int × segmentTickets。算法就最优化了
。 |
|
|
|
|
|