QGAnimatedImageDecodeThreadPool.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // QGAnimatedImageDecodeThreadPool.m
  2. // Tencent is pleased to support the open source community by making vap available.
  3. //
  4. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  5. //
  6. // Licensed under the MIT License (the "License"); you may not use this file except in
  7. // compliance with the License. You may obtain a copy of the License at
  8. //
  9. // http://opensource.org/licenses/MIT
  10. //
  11. // Unless required by applicable law or agreed to in writing, software distributed under the License is
  12. // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  13. // either express or implied. See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #import "QGAnimatedImageDecodeThreadPool.h"
  16. #import "QGAnimatedImageDecodeThread.h"
  17. #import "QGVAPSafeMutableArray.h"
  18. @interface QGAnimatedImageDecodeThreadPool (){
  19. NSMutableArray *_threads;
  20. }
  21. @end
  22. @implementation QGAnimatedImageDecodeThreadPool
  23. + (instancetype)sharedPool {
  24. static QGAnimatedImageDecodeThreadPool *instance;
  25. static dispatch_once_t onceToken;
  26. dispatch_once(&onceToken, ^{
  27. instance = [[QGAnimatedImageDecodeThreadPool alloc] init];
  28. });
  29. return instance;
  30. }
  31. - (instancetype)init {
  32. if (self = [super init]) {
  33. _threads = [QGVAPSafeMutableArray new];
  34. }
  35. return self;
  36. }
  37. /**
  38. 从池子中找出没被占用的线程,如果没有则新建一个
  39. @return 解码线程
  40. */
  41. - (QGAnimatedImageDecodeThread *)getDecodeThread {
  42. QGAnimatedImageDecodeThread *freeThread = nil;
  43. for (QGAnimatedImageDecodeThread *thread in _threads) {
  44. if (!thread.occupied) {
  45. freeThread = thread;
  46. }
  47. }
  48. if (!freeThread) {
  49. freeThread = [[QGAnimatedImageDecodeThread alloc] initWithTarget:self selector:@selector(run) object:nil];
  50. [freeThread start];
  51. [_threads addObject:freeThread];
  52. }
  53. return freeThread;
  54. }
  55. - (void)run{
  56. //线程保活
  57. @autoreleasepool {
  58. [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
  59. NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  60. [runLoop run];
  61. }
  62. }
  63. @end