Skip to content

Commit

Permalink
优化iOS/OSX平台多线程下会话的生成规则
Browse files Browse the repository at this point in the history
  • Loading branch information
vimfung committed Apr 17, 2019
1 parent f0d999f commit 52fc222
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
28 changes: 22 additions & 6 deletions Source/iOS_OSX/Code/LSCContext.m
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ - (instancetype)initWithConfig:(LSCConfig *)config
if (self = [super init])
{
_config = config;
self.sessionMap = [NSMutableDictionary dictionary];
self.methodBlocks = [NSMutableDictionary dictionary];

self.optQueue = [[LSCOperationQueue alloc] init];
Expand Down Expand Up @@ -105,9 +106,12 @@ - (void)dealloc

- (LSCSession *)currentSession
{
if (_currentSession)
NSString *tid = [NSString stringWithFormat:@"%p", [NSThread currentThread]];
LSCSession *session = self.sessionMap[tid];

if (session)
{
return _currentSession;
return session;
}

return _mainSession;
Expand Down Expand Up @@ -533,9 +537,16 @@ - (void)raiseExceptionWithError:(LSCError *)error
- (LSCSession *)makeSessionWithState:(lua_State *)state
lightweight:(BOOL)lightweight
{
NSString *tid = [NSString stringWithFormat:@"%p", [NSThread currentThread]];
LSCSession *session = [[LSCSession alloc] initWithState:state context:self lightweight:lightweight];
session.prevSession = _currentSession;
self.currentSession = session;

LSCSession *prevSession = self.sessionMap[tid];
if (prevSession)
{
session.prevSession = prevSession;
}

[self.sessionMap setObject:session forKey:tid];

return session;
}
Expand All @@ -545,9 +556,14 @@ - (void)destroySession:(LSCSession *)session
[self raiseExceptionWithError:session.lastError];
[session clearError];

if (_currentSession == session)
NSString *tid = [NSString stringWithFormat:@"%p", [NSThread currentThread]];
if (session.prevSession)
{
[self.sessionMap setObject:session.prevSession forKey:tid];
}
else
{
self.currentSession = session.prevSession;
[self.sessionMap removeObjectForKey:tid];
}
}

Expand Down
7 changes: 6 additions & 1 deletion Source/iOS_OSX/Code/LSCContext_Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
获取当前会话,每次与Lua进行交互都会产生一个会话,该会话在交互结束后销毁.
借助该会话可以解析Lua传递的参数,并且可以给Lua设置返回值
*/
@property (nonatomic, strong) LSCSession *currentSession;
@property (nonatomic, strong, readonly) LSCSession *currentSession;

/**
获取主会话对象
Expand All @@ -52,6 +52,11 @@
*/
@property (nonatomic, strong) LSCExportsTypeManager *exportsTypeManager;

/**
会话表,用于记录不同线程下的会话链,key为线程标识。
*/
@property (nonatomic, strong) NSMutableDictionary<NSString *, LSCSession *> *sessionMap;

/**
通过状态设置当前会话
Expand Down

0 comments on commit 52fc222

Please sign in to comment.